将列表元素作为Python中的单个项返回 [英] Return elements of list as individual items in Python
问题描述
Stackoverflow的大家好,
Hi people of Stackoverflow,
我有一个计算列表的函数,我想单独返回列表的每个元素,就像这样(接收此返回值的函数旨在处理未定义数量的参数):
I have a function which calculates a list and I want to return each element of the list individually, like so (the function receiving this return is designed to handle an undefined number of parameters):
def foo():
my_list = [1,2,3,4]
return 1,2,3,4
列表中的元素数量未定义,所以我不能这样做:
The number of elements in the list is undefined so I can't do:
return my_list[0], my_list[1], ...
我认为必须有一个简单的解决方案,但是我似乎无法将其束之高阁. 有什么建议?谢谢!
I think there must be an easy solution to this but I can't seem to wrap my head around it. Any suggestions? Thanks!
谢谢您的回答,所以这是我的问题的扩展,这实际上是我的问题:
Thanks for your answers, so here is the extension to my problem, which is really my problem:
def foo():
my_list = [1,2,3,4]
return "any_other_value", my_list
所以,我想要的是当我调用foo()
,bar = foo()
,bar[0] = "any_other_value", bar[1] = 1, bar[2]=3, bar[3] = 4
时. my_list
的长度不确定(此处只有4个元素).
So, what I want is that when I call foo()
, bar = foo()
, bar[0] = "any_other_value", bar[1] = 1, bar[2]=3, bar[3] = 4
. And my_list
is of undetermined length (here it has only 4 elements).
推荐答案
您正在使事情变得过于复杂.只需按您的方式做即可(我想您可以使用tuple(my_list)
将其转换为显示方式,但这是不必要的):
You are overcomplicating things. Just do what you were doing as (I suppose you could convert it to how you are showing it with tuple(my_list)
but it is unnecessary):
return my_list
这是您需要做的所有事情,因为当您调用带有未定义数量参数的函数时,您可以这样调用它:
This is all you need to do because when you call that function that takes an undefined number of parameters, you can just call it as such:
function_with_undefined_number_of_params(*foo())
*
将返回的list
解压缩为单独的参数.
The *
unpacks the returned list
into separate arguments.
这篇关于将列表元素作为Python中的单个项返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!