Python:解压到未知数量的变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/431944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: unpack to unknown number of variables?
提问by Nope
How could I unpack a tuple of unknown to, say, a list?
我怎么能解开一个未知的元组,比如一个列表?
I have a number of columns of data and they get split up into a tuple by some function. I want to unpack this tuple to variables but I do not know how many columns I will have. Is there any way to dynamically unpack it to as many variables as I need?
我有许多数据列,它们被某个函数分成一个元组。我想将此元组解包为变量,但我不知道我将有多少列。有什么方法可以根据需要将其动态解压缩为多个变量?
Thanks for your help :)
谢谢你的帮助 :)
采纳答案by PEZ
Unpack the tuple to a list?
将元组解包到列表中?
l = list(t)
回答by Evan Fosmark
You can use the asterisk to unpack a variable length. For instance:
您可以使用星号来解包可变长度。例如:
foo, bar, *other = funct()
This should put the first item into foo
, the second into bar
, and all the rest into other
.
这应该把第一项放入foo
,第二项放入,bar
其余的都放入other
。
Update:I forgot to mention that this is Python 3.0 compatible only.
更新:我忘了提到这仅与 Python 3.0 兼容。
回答by Brian Clapper
Do you mean you want to create variables on the fly? How will your program know how to reference them, if they're dynamically created?
你的意思是你想动态创建变量吗?如果它们是动态创建的,您的程序将如何知道如何引用它们?
Tuples have lengths, just like lists. It's perfectly permissable to do something like:
元组有长度,就像列表一样。完全允许执行以下操作:
total_columns = len(the_tuple)
You can also convert a tuple to a list, though there's no benefit to doing so unless you want to start modifying the results. (Tuples can't be modified; lists can.) But, anyway, converting a tuple to a list is trivial:
您还可以将元组转换为列表,但这样做没有任何好处,除非您想开始修改结果。(元组不能修改;列表可以。)但是,无论如何,将元组转换为列表是微不足道的:
my_list = list(the_tuple)
There areways to create variables on the fly (e.g., with eval
), but again, how would you know how to refer to them?
有有办法来动态创建(例如,变量eval
),但同样,你怎么会知道如何参考呢?
I think you should clarify exactly what you're trying to do here.
我认为您应该在这里明确说明您要做什么。