简体   繁体   中英

Accessing MxM numpy array that is first index of a tuple

As stated in the title, I have a list of tuples that look like (numpy_array,id) where the numpy array is mx m. I need to access each element of the numpy array (ie all m^2 of them) but am having a tough time doing this without unpacking the tuple.

I would rather not unpack the tuple because of how much data it is/how long that would take due to the amount of data.

If I unpack the tuple the code would look like below, is there a way to index this so that I don't need to unpack?

    for x in range(length):
        for y in range(length):
            if(instance1[x][y]==instance2[x][y]):
                distance -=1

If you just want to access directly to a element in a specific position of the ndimensional numpy array, you can just use a .
For example:
I want to access the element in the third column of the first row of a 3x3 array c , then I will do c[0,2] .

c = np.random.rand( 3,3 )
print(c)
print( 'Element:', c[0,2])

Check the official doc Numpy Indexing

_Update__
In case of a list of tuples you should index for each data structure

import numpy as np    
a =[ 
        ( np.random.rand( 2,2 ), 0 ), #first  tuple
        ( np.random.rand( 2,2 ), 2 ), #second  tuple
        ( np.random.rand( 2,2 ), 3 ), # ...
        ( np.random.rand( 2,2 ), 1 )
        ]

    print( np.shape(a) )    # accessing list a
    # (4,2)
    print( np.shape(a[0]) ) # accessing the first tuple in a
    # (2)
    print( np.shape(a[0][0]) ) # accessing the 2x2 array inside the first tuple
    # (2,2)
    print( np.shape(a[0][0][0,1]) ) # accessing the [0,1] element inside the array
    # ()

    #another example
    c = ( np.array([ [1,2,3],[4,5,6],[7,8,9] ]), 8 )
    print( c[0][0,2] ) # output: 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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