简体   繁体   English

访问作为元组的第一个索引的MxM numpy数组

[英]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. 如标题中所述,我有一个看起来像(numpy_array,id)的元组列表,其中numpy数组是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. 我需要访问numpy数组的每个元素(即它们中的所有m ^ 2),但是在不拆开元组的情况下很难做到这一点。

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 ndimensional indexing . 如果只想直接访问n维numpy数组特定位置的元素,则可以使用n维索引
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] . 我想访问3x3数组c第一行的第三列中的元素,那么我将执行c [0,2]

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

Check the official doc Numpy Indexing 检查官方文档Numpy索引

_Update__ _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

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

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