代码之家  ›  专栏  ›  技术社区  ›  sf8193

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

  •  0
  • sf8193  · 技术社区  · 8 年前

    如标题中所述,我有一个tuples列表,它看起来像(numpy_array,id),其中numpy array是m x m。我需要访问numpy array的每个元素(即所有m^2个元素),但在不解包tuple的情况下,这样做很困难。

    我不愿意解包这个元组,因为它有多少数据/由于数据量的原因需要多长时间。

    如果我解包tuple,代码如下所示,有没有一种方法可以索引这个,这样我就不需要解包了?

        for x in range(length):
            for y in range(length):
                if(instance1[x][y]==instance2[x][y]):
                    distance -=1
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   GianAnge    8 年前

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

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

    检查官方文件 Numpy Indexing

    _更新__
    对于元组列表,应为每个数据结构编制索引。

    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