分配列表的多个值 [英] Assign multiple values of a list

查看:68
本文介绍了分配列表的多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想知道是否存在一种"pythonic"方式将列表中的值分配给元素?更清楚地说,我要的是这样的东西:

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)

因此:

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]

推荐答案

只需将其键入:

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

在将iterable分配给上述多个变量时,Python使用assignment unpacking.

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

Python3.x中,此功能已得到扩展,因为您也可以使用star运算符解压缩小于iterable长度的多个变量:

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]

这篇关于分配列表的多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆