Tuple as index of multidimensional array

前端 未结 2 979
我在风中等你
我在风中等你 2020-12-18 03:51

I found a very similar question to mine, but not exactly the same. This one: here However in ntimes\'s case the size of the array matches the number of the dimensions the tu

相关标签:
2条回答
  • 2020-12-18 04:04

    You can also pass in your first tuple alone to get the slice of interest, then index it seprately:

    from numpy.random import rand
    big_array=rand(3,3,4,5)
    chosen_slice = (2,2)
    
    >>> big_array[ chosen_slice ]
    array([[ 0.96281602,  0.38296561,  0.59362615,  0.74032818,  0.88169483],
           [ 0.54893771,  0.33640089,  0.53352849,  0.75534718,  0.38815883],
           [ 0.85247424,  0.9441886 ,  0.74682007,  0.87371017,  0.68644639],
           [ 0.52858188,  0.74717948,  0.76120181,  0.08314177,  0.99557654]])
    
    >>> chosen_part = (1,1)
    
    >>> big_array[ chosen_slice ][ chosen_part ]
    0.33640088565877657
    

    That may be slightly more readable for some users, but otherwise I'd lean towards mgilson's solution.

    0 讨论(0)
  • 2020-12-18 04:15

    Since you're using numpy:

    big_array[tup+(3,2)]
    

    should work. When you call __getitem__ (via the square brackets), the stuff is passed to __getitem__ as a tuple. You just need to construct the tuple explicitly here (adding tuples together concatenates into a new tuple) and numpy will do what you want.

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