Unpacking an array in python

天大地大妈咪最大 提交于 2020-05-13 05:13:20

问题


I have a variable data that is of (1000L, 3L) shape and I do the following to get the coordinates:

x = data[:,0]
y = data[:,1]
z = data[:,2]

Is there a way to unpack them? I tried but it doesn't work:

[x,y,z] = data1[:,0:3]

回答1:


You could simply transpose it before unpacking:

x, y, z = data.T

Unpacking "unpacks" the first dimensions of an array and by transposing the your array the size-3 dimension will be the first dimension. That's why it didn't work with [x, y, z] = data1[:, 0:3] because that tried to unpack 1000 values into 3 variables.




回答2:


You could unpack using zip:

x, y, z = zip(*data[:, :3])


来源:https://stackoverflow.com/questions/46133444/unpacking-an-array-in-python

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