繁体   English   中英

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

[英]Accessing MxM numpy array that is first index of a tuple

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

我宁愿不解开元组,因为它需要多少数据/由于数据量需要多长时间。

如果我打开元组的代码,则代码如下所示,有没有办法对此进行索引,这样我就不需要解包了?

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

如果只想直接访问n维numpy数组特定位置的元素,则可以使用n维索引
例如:
我想访问3x3数组c第一行的第三列中的元素,那么我将执行c [0,2]

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

检查官方文档Numpy索引

_Update__
如果有元组列表,则应为每个数据结构建立索引

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