带有输入参数的函数,会将它们转换成其主体内的列表

function with input parameters that will convert them into a list inside its body

有没有一种方法可以创建如下所示的函数,然后将这些参数添加到函数体内的列表中?

def create_list(x, y, z, w, t):

在这里你必须在你的函数中使用 *args,它会被定义成这样

def make_list(*args):
    return list(args)

print(make_list(1,2,3, "Spiderman", ("Gilfoyle", "Dinesh", "Richard"), {"wizardName": "Harry Potter", "age": 21}))

以上代码的输出

[1, 2, 3, 'Spiderman', ('Gilfoyle', 'Dinesh', 'Richard'), {'wizardName': 'Harry Potter', 'age': 21}]

在这里你可以传递任意数量的任何类型的参数,它们将被转换成一个列表并返回给你。我们需要写 return list(args) 因为它 returns 默认是一个元组。由于您需要一个列表,我们需要调用 list() 函数。

参考

  1. *args and **kwargs in python