在不知道序列长度的情况下,在Python中展开多个赋值
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 Q is not numpy specfic; indeed, i would prefer a pure python solution.)
(我的Q并不麻木;实际上,我更喜欢纯python解决方案。
W/r/t the piece of code i'm looking at now, i see two complications on that straightforward scenario:
W/r/t我现在看到的这段代码,我看到了两个复杂的情况:
i usually won't know the shape of M; and
我通常不知道M的形状;和
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 be able to do is, for instance, 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 = [].
回到上面的5 x4数组中,我很想能够做的是,例如,分配的前三行M a,b和c分别(如上图),其余的行(我不知道有多少会有,只是一些正整数)到一个容器,all_the_rest =[]。
I'm not sure if i have explained this clearly; in any event, if i get feedback i'll promptly edit my Question.
我不确定我是否解释得很清楚;无论如何,如果我得到反馈,我会立即修改我的问题。
2 个解决方案
#1
20
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:]
更多相关文章
- 无法安装ndg-httpsclient或者我的解决方案错误
- Linux无法连接网络解决方案
- Media-S 简介(一个开源的DRM解决方案)
- AppScan安全问题解决方案
- PLSQL乱码解决方案
- 数据库不支持中文解决方案(mysql)
- Mysql替代解决方案Cassandra
- [置顶] Android屏幕适配解决方案
- 物流货运移动APP解决方案