循环遍历数组并使用索引获取多个维度

时间:2017-06-14 09:46:39

标签: python numpy

参考我之前(已解决)的问题(link),我现在想在多维数组上执行该操作。

vertices = [[ 1.25, 4.321, -4], [2, -5, 3.32], [23.3, 43, 12], [32, 4, -23]]

newedges = [[1, 3, 2, 0], [2, 1, 3, 0], [1, 2, 0, 3]]

newresult = [[[2, -5, 3.32], [32, 4, -23], [23.3, 43, 12], [ 1.25, 4.321, -4]], [[23.3, 43, 12], [2, -5, 3.32], [32, 4, -23], [ 1.25, 4.321, -4]], [[2, -5, 3.32], [23.3, 43, 12], [ 1.25, 4.321, -4], [32, 4, -23]]]

我想找回一个与#34; newedges"相同形状的数组。但是索引被顶点替换( - > newresult)。

我试过了:

list = ()
arr = np.ndarray(newedges.shape[0])

for idx, element in enumerate(newedges):

    arr[idx] = vertices[newedges[idx]]

list.append(arr)

但是得到一个索引错误(使用我的真实数据,这就是为什么有一个索引61441):

IndexError: index 61441 is out of bounds for axis 1 with size 2

3 个答案:

答案 0 :(得分:1)

你走了:

import numpy as np

vertices = [[ 1.25, 4.321, -4], [2, -5, 3.32], [23.3, 43, 12], [32, 4, -23]]
vertices= np.array(vertices)
newedges = [[1, 3, 2, 0], [2, 1, 3, 0], [1, 2, 0, 3]]

newresult = []

for edgeset in newedges:
    updatededges = np.take(vertices, edgeset, 0)
    newresult.append(updatededges)

print newresult
"""
newresult = [array([[  2.   ,  -5.   ,   3.32 ],
       [ 32.   ,   4.   , -23.   ],
       [ 23.3  ,  43.   ,  12.   ],
       [  1.25 ,   4.321,  -4.   ]]),

 array([[ 23.3  ,  43.   ,  12.   ],
       [  2.   ,  -5.   ,   3.32 ],
       [ 32.   ,   4.   , -23.   ],
       [  1.25 ,   4.321,  -4.   ]]),

 array([[  2.   ,  -5.   ,   3.32 ],
       [ 23.3  ,  43.   ,  12.   ],
       [  1.25 ,   4.321,  -4.   ],
       [ 32.   ,   4.   , -23.   ]])]
"""

另一个建议:不要使用list之类的python关键字作为变量名。这适用于任何编程语言

答案 1 :(得分:1)

而不是list= (),您必须使用result = []

替换:arr = np.ndarray(newedges.shape[0])

至:arr = np.ndarray(newedges[0]).shape

for idx, element in enumerate(newedges):
    arr[idx] = vertices[newedges[0][idx]]

result.append(arr)

你得到了IndexError,因为你传递了列表vertices[newedges[idx]]的列表,但列出了所需的索引或切片vertices[newedges[0][idx]]

希望这个答案符合您的要求。

答案 2 :(得分:0)

在第3行,你错过了一个]

之前:

newedges = [[1, 3, 2, 0], [2, 1, 3, 0], [1, 2, 0, 3]

之后:

newedges = [[1, 3, 2, 0], [2, 1, 3, 0], [1, 2, 0, 3]]

如果不这样做,则第5行被视为字符串。

然后你还有其他问题,看看它是什么,使用that,你的程序已经在里面,向前推进并等待错误

相关问题