Iterate over *args?

后端 未结 7 1429
借酒劲吻你
借酒劲吻你 2020-12-15 07:52

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 u

7条回答
  •  春和景丽
    2020-12-15 07:57

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

提交回复
热议问题