[英]How to get a value from a given n-dim index
我有一些這樣的索引:
ind = [(1,5),(2,2),(3,1)]
我有一個數組:
arr = np.arange(36).reshape(6,6)
我想獲得結果:
arr[1,5], arr[2,2], arr[3,1]
什么是最干凈的方法?
我知道我可以做這樣的事情:
c=np.empty(len(ind))
for i in len(ind):
a,b = ind[i]
c[i] = arr[a,b]
但是我想要一個類似矩陣的方法來解決這個問題,而不是像元素一樣的方法。 有什么建議嗎?
為什么不只使用列表理解:
ind = [(1,5),(2,2),(3,1)]
arr = np.arange(36).reshape(6,6)
result = [arr[i] for i in ind]
如果需要將其轉換為numpy
數組,則可以將結果列表傳遞給它:
result = np.array([arr[i] for i in ind])
你可以直接寫
c=[]
for i in range(len(ind)):
c.append( arr[ ind[i][0], ind[i][1] ] )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.