简体   繁体   中英

How to use sequence unpacking with a sequence of variable length?

If I know the length of a list in advance, I can use sequence unpacking to assign variable the elements of the list thus:

my_list = [1,2,3]

x, y, z = my_list

If I don't know the length of the list in advance, how can I assign variables to the elements of the list using sequence unpacking? If for argument's sake I don't care how the variables are named, can I first get the length of the list and then unpack to this amount of arbitrarily-named variables?

Certainly not recommend but possible:

my_list = [1, 2, 3]
for counter, value in enumerate(my_list):
    exec 'a{} = {}'.format(counter, value)
print a0, a1, a2

Output:

1 2 3

Or use Python 3:

>>> a, *rest = my_list
>>> a
1
>>> rest
[2, 3]

you can force the length of the list to unpacking to the size you want like this

>>> my_list=range(10)
>>> a,b,c = my_list[:3]
>>> a
0
>>> b
1
>>> c
2
>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 

if they are less you get a error, otherwise you take the 3 first elements

to the case of less elements you can do something like this

>>> my_list=[1,2]
>>> x,y,z=(my_list[:3] +[-1]*3)[:3]
>>> x
1
>>> y
2
>>> z
-1
>>> 

have a list with default values that you concatenate to the sub-list of my_list and from the result you take what you need

The right answer is that you should leave these elements in a list. This is what a list is for.

The wrong answer is to add local variables in a roundabout way. For Python 3:

ctr = 0
for value in my_list:
    __builtins__.locals()['my_list_{}'.format(ctr)] = value
    ctr += 1

If my_list has n items, this will create variables my_list_0, my_list_1, ..., my_list_{n-1} .

Please don't do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM