迭代*args?

2024-06-26 00:24:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,我正在处理的地方,我需要接受多个参数,然后迭代它们来执行操作。我开始定义一个函数并使用*args。到目前为止,我得到了如下信息:

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

我要做的是把来自*args的参数放到一个列表中,我可以遍历这个列表。我在StackOverflow和Google上都看过其他问题,但我似乎找不到我想做什么的答案。提前谢谢你的帮助。


Tags: 函数脚本信息列表参数that定义def
3条回答

要获得精确的语法:

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视为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引用)。

相关问题 更多 >