函数中可变数量的参数

时间:2018-02-23 11:39:49

标签: python function arguments multiple-arguments

是否可以运行这样的函数:

def call(a,*alphabets,*numbers):
    print(a)
    print(alphabets)
    print(numbers)

我收到以下错误:

  File "<ipython-input-331-ddaef8a7e66f>", line 1
    def call(a,*alphabets,*numbers):
                          ^
SyntaxError: invalid syntax

有人可以告诉我是否有其他方法可以做到这一点?

1 个答案:

答案 0 :(得分:4)

非常简单:要求调用者传递两个列表(或元组或其他):

def call(a,alphabets=None,numbers=None):
    if alphabets is None:
        alphabets = []
    if numbers is None:
        numbers = []
    print(a)
    print(alphabets)
    print(numbers)


call("?")
call("?", ["a", "b", "c"])
call("?", ["a", "b", "c"], (1, 2, 3))
call("?"), None, (1, 2, 3))
# etc