Unpacking tuples/arrays/lists as indices for Numpy Arrays

后端 未结 4 1293
死守一世寂寞
死守一世寂寞 2020-12-01 12:22

I would love to be able to do

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

and get

<         


        
相关标签:
4条回答
  • 2020-12-01 12:40

    It's easier than you think:

    >>> import numpy
    >>> A = numpy.array(((1,2),(3,4)))
    >>> idx = (0,0)
    >>> A[idx]
    1
    
    0 讨论(0)
  • 2020-12-01 12:52

    Indexing an object calls:

    object.__getitem__(index)
    

    When you do A[1, 2], it's the equivalent of:

    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.

    If you happen to index with a list, it might not index the same, as [1, 2] != (1, 2)

    0 讨论(0)
  • 2020-12-01 13:00

    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, baz you would simply say foo[t].

    0 讨论(0)
  • 2020-12-01 13:06

    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.

    0 讨论(0)
提交回复
热议问题