5

我想附加一个带有函数返回值列表的表,其中一些是元组:

def get_foo_bar():
    # do stuff
    return 'foo', 'bar'

def get_apple():
    # do stuff
    return 'apple'

table = list()
table.append([get_foo_bar(), get_apple()])

这产生:

>>> table
[[('foo', 'bar'), 'apple']]

但我需要将返回的元组解压缩到该列表中,如下所示:

[['foo', 'bar', 'apple']]

由于解包函数调用[*get_foo_bar()]不起作用,我分配了两个变量来接收元组的值并附加它们:

foo, bar = get_foo_bar()
table.append([foo, bar, get_apple()])

这有效,但可以避免吗?

4

1 回答 1

7

使用.extend()

>>> table.extend(get_foo_bar())
>>> table.append(get_apple())
>>> [table]
[['foo', 'bar', 'apple']]

或者,您可以连接元组:

>>> table = []
>>> table.append(get_foo_bar() + (get_apple(),))
>>> table
[('foo', 'bar', 'apple')]
于 2013-07-01T09:48:15.263 回答