gpt4 book ai didi

python - 将部分结果追加到python列表中

转载 作者:行者123 更新时间:2023-11-30 23:35:18 25 4
gpt4 key购买 nike

有一些方法,它输出两个变量,例如:

def some_method():
#some calculations
return first_value, second_value

现在我想将一行结果放入变量和列表中(将 first_value 放入某个变量,并将 second_value 作为新元素添加到列表中)。

我知道我可以做这样的事情:

def some_method(list):
#some calculations
return first_value, list+[second_value]

然后:

some_variable, list = some_method(list)

但是有没有机会在一行中完成它并且不传递列表作为方法参数?

最佳答案

你能返回列表中的第二个值吗?

像这样:

>>> L = [1, 2, 3]
>>> def bar():
... return 'shenanigan', [4]
...
>>> myVar, L[len(L):] = bar()
>>> L
[1, 2, 3, 4]

实际上,您也可以将第二个返回值分配给一个中间变量,然后只使用 list.append(),使用两行。

关于python - 将部分结果追加到python列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17464468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com