遍历* args? [英] Iterate over *args?
问题描述
我有一个正在处理的脚本,需要在其中接受多个参数,然后遍历它们以执行操作.我开始定义函数并使用* args.到目前为止,我有类似下面的内容:
I have a script I'm working on where I need to accept multiple arguments and then iterate over them to perform actions. I started down the path of defining a function and using *args. So far I have something like below:
def userInput(ItemA, ItemB, *args):
THIS = ItemA
THAT = ItemB
MORE = *args
我想做的是将* args中的参数放入一个可以迭代的列表中.我在StackOverflow和Google上都看过其他问题,但似乎找不到我想要做的答案.预先感谢您的帮助.
What I'm trying to do is get the arguments from *args into a list that I can iterate over. I've looked at other questions on StackOverflow as well as on Google but I can't seem to find an answer to what I want to do. Thanks in advance for the help.
推荐答案
获得您的精确度语法:
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
You remove the *
in front of args
in the assignment to MORE
. Then MORE becomes a tuple with the variable length contents of args
in the signature of userInput
输出:
this that ('more1', 'more2', 'more3')
正如其他人所述,将args
视为可迭代的对象更为常见:
As others have stated, it is more usual to treat args
as an 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
这篇关于遍历* args?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!