Python: unpack to unknown number of variables?

后端 未结 3 1189
小蘑菇
小蘑菇 2021-01-04 07:14

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

3条回答
  •  有刺的猬
    2021-01-04 07:50

    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.

提交回复
热议问题