【问题标题】:How do you enter a list as a parameter without defining what the length of the list will be?如何在不定义列表长度的情况下输入列表作为参数?
【发布时间】:2015-10-19 17:32:35
【问题描述】:

例如,这是一个接受 5 个参数并颠倒顺序的函数

def reverseList(a,b,c,d,e): 
    normalList = [a,b,c,d,e] 
    reverseList = reversed(normalList) 
    printedList = [] 
    for eachit in reverseList:
        printedList.append(eachit)

    print "This is the list that was entered: %r" % (normalList)
    print "This is the same list, but in reverse: %r" % (printedList)

我是新手,所以我不知道如何输入“自定义”列表,例如不限制函数中可以输入多少个数字。

【问题讨论】:

  • 你可以使用*args,但在这种情况下,我建议只传入一个列表...

标签: python


【解决方案1】:

只需传递一个列表并返回一个反转函数的列表:

>>> def reverseList(li):
...    return list(reversed(li))
... 
>>> reverseList(['a', 'b', 'c'])
['c', 'b', 'a']

适用于任意长度的列表。


或者,正如 cmets 中指出的那样:

>>> def reverseList(li):
...    return li[::-1]

如果您正在寻找对variable length of arguments 而不是列表的支持,请使用*args 和“splat”*,这意味着您的函数采用长度未知的元组(而不是命名的位置参数):

>>> def reverseArgs(*args):
...    return args[::-1]
... 
>>> reverseArgs('a', 'b', 'c', 'd')
('d', 'c', 'b', 'a')

【讨论】:

  • 使用 li[::-1] 。最好的方式reverse
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
相关资源
最近更新 更多