python 将元组/数组/列表解包为 Numpy 数组的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2444923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:40:04  来源:igfitidea点击:

Unpacking tuples/arrays/lists as indices for Numpy Arrays

pythonnumpy

提问by ntimes

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. Converting to a tuple as Alok suggests does the trick.

编辑:感谢您的答复。在我的程序中,我使用 Numpy 数组而不是元组进行索引并得到奇怪的结果。正如 Alok 建议的那样转换为元组可以解决问题。

采纳答案by Vicki Laidler

It's easier than you think:

这比你想象的要容易:

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

回答by Alok Singhal

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.

除非你有一个更复杂的用例,不像这个例子那么简单,否则以上应该适用于所有数组。

回答by lunixbochs

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 mightnot index the same, as [1, 2] != (1, 2)

如果您碰巧使用列表进行索引,则它的索引可能与 [1, 2] != (1, 2) 不同

回答by Mike Graham

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)]. So if you have a tuple t = bar, bazyou would simply say foo[t].

不需要解包——当你在[and之间有逗号时],你正在创建一个元组,而不是传递参数。foo[bar, baz]相当于foo[(bar, baz)]。因此,如果您有一个元组,t = bar, baz您只需说foo[t].