简体   繁体   English

解压缩元组/数组/列表作为Numpy Arrays的索引

[英]Unpacking tuples/arrays/lists as indices for Numpy Arrays

I would love to be able to do 我很乐意能够做到

>>> A = numpy.array(((1,2),(3,4)))
>>> idx = (0,0)
>>> A[*idx]

and get 得到

1

however this is not valid syntax. 但这不是有效的语法。 Is there a way of doing this without explicitly writing out 有没有明确写出来这样做的方法

>>> A[idx[0], idx[1]]

?

EDIT: Thanks for the replies. 编辑:谢谢你的回复。 In my program I was indexing with a Numpy array rather than a tuple and getting strange results. 在我的程序中,我使用Numpy数组而不是元组进行索引并得到奇怪的结果。 Converting to a tuple as Alok suggests does the trick. 转换为Alok建议的元组就可以了。

Try 尝试

A[tuple(idx)]

Unless you have a more complex use case that's not as simple as this example, the above should work for all arrays. 除非你有一个更复杂的用例并不像这个例子那么简单,否则上面应该适用于所有数组。

It's easier than you think: 它比你想象的容易:

>>> import numpy
>>> A = numpy.array(((1,2),(3,4)))
>>> idx = (0,0)
>>> A[idx]
1

Indexing an object calls: 索引对象调用:

object.__getitem__(index)

When you do A[1, 2], it's the equivalent of: 当你做A [1,2]时,它相当于:

A.__getitem__((1, 2))

So when you do: 所以当你这样做时:

b = (1, 2)

A[1, 2] == A[b]
A[1, 2] == A[(1, 2)]

Both statements will evaluate to True. 两个语句都将评估为True。

If you happen to index with a list, it might not index the same, as [1, 2] != (1, 2) 如果您碰巧使用列表进行索引,则它可能不会索引相同的内容,如[1,2]!=(1,2)

No unpacking is necessary —when you have a comma between [ and ] , you are making a tuple, not passing arguments. 不需要解压缩 - 当[]之间有逗号时,你正在制作一个元组,而不是传递参数。 foo[bar, baz] is equivalent to foo[(bar, baz)] . foo[bar, baz]相当于foo[(bar, baz)] So if you have a tuple t = bar, baz you would simply say foo[t] . 所以,如果你有一个元组t = bar, baz那么你只需要说foo[t]

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

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