Multiple Unpacking Assignment in Python when you don't know the sequence length

我怕爱的太早我们不能终老 提交于 2019-11-27 22:57:00
Ignacio Vazquez-Abrams

Python 3.x can do this easily:

a, b, *c = someseq

Python 2.x needs a bit more work:

(a, b), c = someseq[:2], someseq[2:]

Syntax for this is added to Python 3

>>> # Python 3.x only
>>> a, b, *c = range(10)
>>> a
0
>>> b
1
>>> c
[2, 3, 4, 5, 6, 7, 8, 9]

but no similar solution exists in Python 2.

You can of course do

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

or other similar solutions.

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