2024-06-26 00:24:08 发布
网友
我有一个脚本,我正在处理的地方,我需要接受多个参数,然后迭代它们来执行操作。我开始定义一个函数并使用*args。到目前为止,我得到了如下信息:
def userInput(ItemA, ItemB, *args): THIS = ItemA THAT = ItemB MORE = *args
我要做的是把来自*args的参数放到一个列表中,我可以遍历这个列表。我在StackOverflow和Google上都看过其他问题,但我似乎找不到我想做什么的答案。提前谢谢你的帮助。
要获得精确的语法:
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的元组
MORE
*
args
userInput
输出:
this that ('more1', 'more2', 'more3')
正如其他人所说,通常将args视为iterable:
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
如果你这样做:
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/
>>> 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引用)。
要获得精确的语法:
删除分配给
MORE
中*
前面的args
。然后MORE在userInput
的签名中变成一个长度可变的内容为args
的元组输出:
正如其他人所说,通常将
args
视为iterable:输出:
如果你这样做:
其他信息:http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
编辑:另请参见How to use *args and **kwargs in Python(由Jeremy D和subhacom引用)。
相关问题 更多 >
编程相关推荐