简体   繁体   English

如何从给定的n维索引中获取值

[英]How to get a value from a given n-dim index

I have some index like this: 我有一些这样的索引:

ind = [(1,5),(2,2),(3,1)]

and I have an array: 我有一个数组:

arr = np.arange(36).reshape(6,6)

and I would like to obtain the result: 我想获得结果:

arr[1,5], arr[2,2], arr[3,1]

What's the cleanest method? 什么是最干净的方法?

I know I can do something like this: 我知道我可以做这样的事情:

c=np.empty(len(ind))
for i in len(ind):
    a,b = ind[i]
    c[i] = arr[a,b]

But I would like a more matrix-like method to deal with this problem, but not element-like method. 但是我想要一个类似矩阵的方法来解决这个问题,而不是像元素一样的方法。 any suggestion? 有什么建议吗?

Why not just use a list comprehension: 为什么不只使用列表理解:

ind = [(1,5),(2,2),(3,1)]
arr = np.arange(36).reshape(6,6)

result = [arr[i] for i in ind]

If you need to turn it into an numpy array you can just pass the resulting list to it: 如果需要将其转换为numpy数组,则可以将结果列表传递给它:

result = np.array([arr[i] for i in ind])

you can write directly 你可以直接写

c=[]
for i in range(len(ind)):
    c.append( arr[ ind[i][0], ind[i][1] ] )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM