提问人:AP257 提问时间:8/14/2010 最后编辑:wjandreaAP257 更新时间:11/27/2022 访问量:249105
将列表传递给函数以充当多个参数 [duplicate]
Pass a list to a function to act as multiple arguments [duplicate]
问:
在需要项目列表的函数中,如何在不出现错误的情况下传递 Python 列表项?
my_list = ['red', 'blue', 'orange']
function_that_needs_strings('red', 'blue', 'orange') # works!
function_that_needs_strings(my_list) # breaks!
肯定有办法扩大列表,并在蹄子上传递功能吗?我认为这被称为“开箱”。'red','blue','orange'
答:
362赞
Jochen Ritzel
8/14/2010
#1
function_that_needs_strings(*my_list) # works!
您可以在此处阅读有关它的所有信息: 解压缩参数列表 - Python 教程
50赞
Martijn Pieters
12/18/2013
#2
是的,您可以使用 (splat) 语法:*args
function_that_needs_strings(*my_list)
其中可以是任何可迭代对象;Python 将遍历给定的对象,并将每个元素用作函数的单独参数。my_list
请参阅调用表达式文档。
还有一个关键字参数等效项,使用两个星号:
kwargs = {'foo': 'bar', 'spam': 'ham'}
f(**kwargs)
并且有等效的语法用于在函数签名中指定 catch-all 参数:
def func(*args, **kw):
# args now holds positional arguments, kw keyword arguments
19赞
vishes_shell
9/5/2016
#3
从 Python 3.5 开始,您可以解压缩无限数量的 s。list
所以这将起作用:
a = ['1', '2', '3', '4']
b = ['5', '6']
function_that_needs_strings(*a, *b)
评论
1赞
answerSeeker
10/5/2017
我怎样才能用 python 2.7 或 3.4 做同样的事情?
3赞
azalea
1/3/2019
@answerSeeker效率不高,但是function_that_needs_strings(*(a+b))
0赞
TheTechRobo the Nerd
2/12/2021
哇,简直不敢相信你在那之前做不到。
0赞
limitedeternity
12/9/2021
@answerSeeker效率更高:function_that_needs_strings(*itertools.chain(a, b))
评论