循环数组并通过索引获得多个维度

2024-05-15 13:53:02 发布

您现在位置:Python中文网/ 问答频道 /正文

关于我之前的问题(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]]]

我想得到一个与“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

Tags: gtfornplink数组list形状ndarray
3条回答

而不是这个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是因为您传递了listvertices[newedges[idx]]的列表,但是list需要索引或切片vertices[newedges[0][idx]]

希望这个答案是你想要的。你知道吗

在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,因为您的程序已经在里面了,请按“前进”并等待错误

给你:

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关键字作为变量名。这适用于任何编程语言

相关问题 更多 >