在 Python 中解压列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3480184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:16:55  来源:igfitidea点击:

Unpack a list in Python?

pythonlistargument-passing

提问by AP257

I think 'unpack' might be the wrong vocabulary here - apologies because I'm sure this is a duplicate question.

我认为这里的“解包”可能是错误的词汇 - 抱歉,因为我确定这是一个重复的问题。

My question is pretty simple: in a function that expects a list of items, how can I pass a Python list item without getting an error?

我的问题很简单:在需要项目列表的函数中,如何传递 Python 列表项目而不会出错?

my_list = ['red', 'blue', 'orange']
function_that_needs_strings('red', 'blue', 'orange') # works!
function_that_needs_strings(my_list) # breaks!

Surely there must be a way to expand the list, and pass the function 'red','blue','orange'on the hoof?

肯定有一种方法可以扩展列表,并'red','blue','orange'在蹄上传递函数?

采纳答案by Jochen Ritzel

回答by Martijn Pieters

Yes, you can use the *args(splat) syntax:

是的,您可以使用*args(splat) 语法:

function_that_needs_strings(*my_list)

where my_listcan be any iterable; Python will loop over the given object and use each element as a separate argument to the function.

wheremy_list可以是任何可迭代的;Python 将遍历给定的对象并将每个元素用作函数的单独参数。

See the call expression documentation.

请参阅调用表达式文档

There is a keyword-parameter equivalent as well, using two stars:

还有一个等效的关键字参数,使用两颗星:

kwargs = {'foo': 'bar', 'spam': 'ham'}
f(**kwargs)

and there is equivalent syntaxfor specifying catch-all arguments in a function signature:

并且在函数签名中指定捕获所有参数有等效的语法

def func(*args, **kw):
    # args now holds positional arguments, kw keyword arguments

回答by vishes_shell

Since Python 3.5 you can unpack unlimited amount of lists.

从 Python 3.5 开始,您可以解压无限数量的lists。

PEP 448 - Additional Unpacking Generalizations

PEP 448 - 额外的解包概括

So this will work:

所以这将起作用:

a = ['1', '2', '3', '4']
b = ['5', '6']
function_that_needs_strings(*a, *b)