如何在Python中将第二个返回值直接附加到列表中

2024-05-17 01:13:03 发布

您现在位置:Python中文网/ 问答频道 /正文

如果一个函数返回两个值,如何将第二个值直接从函数结果附加到列表中? 像这样:

def get_stuff():
    return 'a string', [1,2,3,5]

all_stuff = [6,7]
# How do I add directly from the next line, without the extra code?
_, lst = get_stuff()
all_stuff += lst

Tags: the函数fromadd列表getstringreturn
2条回答

试试all_stuff += zip(get_stuff())[1]

可以使用与列表[]相同的索引对tuple进行索引。因此,如果需要第二个元素list,可以从函数调用的返回中索引元素[1]。你知道吗

def get_stuff():
    return 'a string', [1,2,3,5]

all_stuff = [6,7]
all_stuff.extend(get_stuff()[1])

输出

[6, 7, 1, 2, 3, 5]

相关问题 更多 >