Assign multiple values of a list

帅比萌擦擦* 提交于 2019-12-04 08:25:24

问题


I am curious to know if there is a "pythonic" way to assign the values in a list to elements? To be clearer, I am asking for something like this:

myList = [3, 5, 7, 2]

a, b, c, d = something(myList)

So that:

a = 3
b = 5
c = 7
d = 2

I am looking for any other, better option than doing this manually:

a = myList[0]
b = myList[1]
c = myList[2]
d = myList[3]

回答1:


Simply type it out:

>>> a,b,c,d = [1,2,3,4]
>>> a
1
>>> b
2
>>> c
3
>>> d
4

Python employs assignment unpacking when you have an iterable being assigned to multiple variables like above.

In Python3.x this has been extended, as you can also unpack to a number of variables that is less than the length of the iterable using the star operator:

>>> a,b,*c = [1,2,3,4]
>>> a
1
>>> b
2
>>> c
[3, 4]



回答2:


Totally agree with NDevox's answer

a,b,c,d = [1,2,3,4]

I think it is also worth to mention that if you only need part of the list e.g only the second and last element from the list, you could do

_, a, _, b = [1,2,3,4]



回答3:


a, b, c, d = myList is what you want.

Basically, the function returns a tuple, which is similar to a list - because it is an iterable.

This works with all iterables btw.



来源:https://stackoverflow.com/questions/31426095/assign-multiple-values-of-a-list

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