我有一个我正在处理的脚本,我需要接受多个参数,然后迭代它们以执行操作。我开始了定义函数和使用*args的过程。到目前为止,我得到了如下内容:
def userInput(ItemA, ItemB, *args):
THIS = ItemA
THAT = ItemB
MORE = *args我要做的是将*args中的参数放入一个可以迭代的列表中。我已经在StackOverflow和谷歌上查看了其他问题,但我似乎找不到我想做的事情的答案。提前感谢你的帮助。
发布于 2012-03-06 00:41:39
要获得精确语法,请执行以下操作:
def userInput(ItemA, ItemB, *args):
THIS = ItemA
THAT = ItemB
MORE = args
print THIS,THAT,MORE
userInput('this','that','more1','more2','more3')在分配给MORE时,删除args前面的*。然后,MORE成为具有userInput签名中args的可变长度内容的元组
输出:
this that ('more1', 'more2', 'more3')正如其他人所说的那样,更常见的做法是将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') 输出:
this that more1 more2 more3发布于 2012-03-05 23:23:38
>>> 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编辑:参见How to use *args and **kwargs in Python (由Jeremy D和subhacom引用)。
发布于 2012-03-05 23:24:02
如果你这样做了:
def test_with_args(farg, *args):
print "formal arg:", farg
for arg in args:
print "other args:", arg其他信息:http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
https://stackoverflow.com/questions/9569092
复制相似问题