Iterate over *args?

杀马特。学长 韩版系。学妹 提交于 2020-04-04 06:49:07

问题


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

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.


回答1:


Tho get your precise syntax:

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

    print THIS,THAT,MORE


userInput('this','that','more1','more2','more3')

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

Output:

this that ('more1', 'more2', 'more3')

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') 

Output:

this that more1 more2 more3



回答2:


>>> 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

edit: See also How to use *args and **kwargs in Python (As referenced by Jeremy D and subhacom).




回答3:


If you do that :

def test_with_args(farg, *args):
    print "formal arg:", farg
    for arg in args:
        print "other args:", arg

Other information: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/




回答4:


MORE = args

Or, directly:

for arg in args:
    print "An argument:", arg



回答5:


If your question is "how do I iterate over args", then the answer is "the same way you iterate over anything": for arg in args: print arg.




回答6:


Just iterate over args:

def userInput(ItemA, ItemB, *args):
    THIS = ItemA
    THAT = ItemB
    for arg in args:
        print arg



回答7:


First entry in: http://www.google.com/search?q=python+*args viz. http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/ should solve your problem,



来源:https://stackoverflow.com/questions/9569092/iterate-over-args

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!