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

断了今生、忘了曾经 提交于 2019-11-26 23:14:38

问题


The textbook examples of multiple unpacking assignment are something like:

import numpy as NP
M = NP.arange(5)
a, b, c, d, e = M
# so of course, a = 0, b = 1, etc.

M = NP.arange(20).reshape(5, 4)     # numpy 5x4 array
a, b, c, d, e = M
# here, a = M[0,:], b = M[1,:], etc. (ie, a single row of M is assigned each to a through e)

(My question is not numpy specific. Indeed, I would prefer a pure Python solution.)

For the piece of code I'm looking at now, I see two complications on that straightforward scenario:

  • I usually won't know the shape of M; and

  • I want to unpack a certain number of items (definitely less than all items), and I want to put the remainder into a single container

So back to the 5x4 array above, what I would very much like to do is assign the first three rows of M to a, b, and c respectively (exactly as above), and the rest of the rows (I have no idea how many there will be, just some positive integer) to a single container, all_the_rest = [].


回答1:


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:]



回答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.



来源:https://stackoverflow.com/questions/2531776/multiple-unpacking-assignment-in-python-when-you-dont-know-the-sequence-length

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