当您不知道序列长度时,Python 中的多重解包赋值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2531776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple Unpacking Assignment in Python when you don't know the sequence length
提问by doug
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.)
(我的问题并不numpy
具体。确实,我更喜欢纯 Python 解决方案。)
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 singlecontainer
我通常不知道 M 的形状;和
我想解压一定数量的项目(肯定少于所有项目),我想把其余为单一容器
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 = []
.
所以回到上面的 5x4 数组,我非常想做的是将 M 的前三行分别分配给 a、b 和 c(和上面一样),其余的行(我不知道如何将有很多,只是一些正整数)到单个容器,all_the_rest = []
。
回答by Ignacio Vazquez-Abrams
Python 3.x can do this easily:
Python 3.x 可以轻松做到这一点:
a, b, *c = someseq
Python 2.x needs a bit more work:
Python 2.x 需要做更多的工作:
(a, b), c = someseq[:2], someseq[2:]
回答by Mike Graham
Syntax for this is added to Python 3
此语法已添加到 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.
但 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.
或其他类似的解决方案。