Python: unpack to unknown number of variables?

南楼画角 提交于 2019-12-30 08:20:11

问题


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 :)


回答1:


Unpack the tuple to a list?

l = list(t)



回答2:


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.

Update: I forgot to mention that this is Python 3.0 compatible only.




回答3:


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 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.



来源:https://stackoverflow.com/questions/431944/python-unpack-to-unknown-number-of-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!