如何直接将多个返回值添加到Python列表中
如果一个函数返回两个值,我们怎么能直接把这两个值添加到两个不同的列表里呢?就像这样:
def get_stuff():
return [3,4,5], [9,10,11]
stuffed_one = [1,2,3]
stuffed_two = [6,7,8]
# How do I add directly from the next line, without the extra code?
lst_one, lst_two = get_stuff()
stuffed_one += lst_one
stuffed_two += lst_two
假设 get_stuff
这个函数总是返回两个列表(包括空列表)。
2 个回答
0
稍微变通一下使用 for
循环,你可以用 itertools.starmap
。
from itertools import starmap
def get_stuff():
return [3,4,5], [9,10,11]
stuffed_one = [1,2,3]
stuffed_two = [6,7,8]
for _ in starmap(list.extend, zip([stuffed_one, stuffed_two], get_stuff())):
pass
zip
会返回一个迭代器,这个迭代器会提供像 (stuffed_one, [3,4,5])
和 (stuffed_two, [6,7,8])
这样的元组。starmap
会把这些元组当作参数列表,用来依次调用 list.extend
(注意,list.extend(stuffed_one, [1,2,3])
和 stuffed_one.extend([1,2,3])
基本上是一样的)。因为 starmap
返回的是一个迭代器,所以你只需要一种方法来实际调用每次的 list.extend
,这就意味着要用 for
循环来遍历它。
0
就像你做的那样。你得到了一个包含两个列表的元组,提取出这两个列表,然后把它们合并在一起。如果你想的话,可以用zip()这个函数来做得更花哨,但对于两个列表的情况,我觉得没必要这么麻烦。
>>> def foo():
... return [1,2,3], [4,5,6]
...
>>> l1=["a", "b"]
>>> l2=["d", "e"]
>>> l1, l2=map(lambda x: x[0]+x[1], zip((l1, l2), foo()))
>>> l1
['a', 'b', 1, 2, 3]
>>> l2
['d', 'e', 4, 5, 6]
>>>