标签归档:argument-passing

在Python中解压缩列表?

问题:在Python中解压缩列表?

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

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

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

当然,必须有一种方法来扩展列表,并'red','blue','orange'在蹄上传递函数吗?

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?

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?


回答 0

function_that_needs_strings(*my_list) # works!

你可以在这里读到所有和它有关的。

function_that_needs_strings(*my_list) # works!

You can read all about it here.


回答 1

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

function_that_needs_strings(*my_list)

在哪里my_list可以迭代?Python将遍历给定的对象,并将每个元素用作函数的单独参数。

请参阅调用表达式文档

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

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

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

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

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

function_that_needs_strings(*my_list)

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

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 syntax for specifying catch-all arguments in a function signature:

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

回答 2

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

PEP 448-其他拆包概述

所以这将工作:

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

Since Python 3.5 you can unpack unlimited amount of lists.

PEP 448 – Additional Unpacking Generalizations

So this will work:

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