解压到未知数量的变量?
我怎样才能将一个未知的元组解压到一个列表中?
我有许多数据列,它们通过某种函数分成一个元组。 我想将此元组解压为变量,但我不知道我将拥有多少列。 有什么方法可以将其动态解压为我需要的尽可能多的变量吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用星号来解压可变长度,例如:
这应该将第一项放入
foo
,第二个放入bar
,其余所有放入其他
。更新:我忘了提及,这仅兼容 Python 3.0。
You can use the asterisk to unpack a variable length, for instance:
This should put the first item into
foo
, the second intobar
, and all the rest intoother
.Update: I forgot to mention that this is Python 3.0 compatible only.
将元组解压到列表中?
Unpack the tuple to a list?
您的意思是您想动态创建变量吗? 如果它们是动态创建的,您的程序如何知道如何引用它们?
元组有长度,就像列表一样。 完全允许执行以下操作:
您还可以将元组转换为列表,尽管这样做没有任何好处,除非您想开始修改结果。 (元组不能修改;列表可以。)但是,无论如何,将元组转换为列表是微不足道的:
有方法可以动态创建变量(例如,使用
eval< /code>),但同样,您怎么知道如何引用它们?
我认为你应该准确地澄清你想在这里做什么。
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:
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:
There are ways to create variables on the fly (e.g., with
eval
), but again, how would you know how to refer to them?I think you should clarify exactly what you're trying to do here.