迭代*args?

Pau*_*aul 13 python arguments

我有一个脚本,我正在努力,我需要接受多个参数,然后迭代它们来执行操作.我开始定义一个函数并使用*args.到目前为止,我有类似下面的内容:

def userInput(ItemA, ItemB, *args):
    THIS = ItemA
    THAT = ItemB
    MORE = *args
Run Code Online (Sandbox Code Playgroud)

我想要做的是将*args中的参数放入我可以迭代的列表中.我已经在StackOverflow以及Google上查看了其他问题,但我似乎无法找到我想要做的答案.在此先感谢您的帮助.

the*_*olf 16

你得到精确的语法:

def userInput(ItemA, ItemB, *args):
    THIS = ItemA
    THAT = ItemB
    MORE = args

    print THIS,THAT,MORE


userInput('this','that','more1','more2','more3')
Run Code Online (Sandbox Code Playgroud)

你删除了作业*前面的.然后MORE成为一个元组,其签名为可变长度内容argsMOREargsuserInput

输出:

this that ('more1', 'more2', 'more3')
Run Code Online (Sandbox Code Playgroud)

正如其他人所说的那样,将其args视为可迭代更为常见:

def userInput(ItemA, ItemB, *args):    
    lst=[]
    lst.append(ItemA)
    lst.append(ItemB)
    for arg in args:
        lst.append(arg)

    print ' '.join(lst)

userInput('this','that','more1','more2','more3') 
Run Code Online (Sandbox Code Playgroud)

输出:

this that more1 more2 more3
Run Code Online (Sandbox Code Playgroud)


Ste*_*ski 5

>>> def foo(x, *args):
...   print "x:", x
...   for arg in args: # iterating!  notice args is not proceeded by an asterisk.
...     print arg
...
>>> foo(1, 2, 3, 4, 5)
x: 1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)

编辑:另请参阅如何在 Python 中使用 *args 和 **kwargs(由 Jeremy D 和 subhacom 引用)。