【问题标题】:Accessing MxM numpy array that is first index of a tuple访问作为元组的第一个索引的 MxM numpy 数组
【发布时间】:2018-06-14 18:51:00
【问题描述】:

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

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

如果我解压元组,代码如下所示,有没有办法将其编入索引,这样我就不需要解压了?

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

【问题讨论】:

    标签: python numpy indexing tuples


    【解决方案1】:

    如果您只想直接访问 n 维 numpy 数组的特定位置中的元素,您可以使用 n 维索引
    例如:
    我想访问一个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
    

    【讨论】:

    • 嗨!感谢您的帮助。我仍然有点困惑,因为当我尝试在 lists = [(c,'square')] 这样的元组中执行此操作时,我在尝试执行 print(lists[0][0,2]) 时遇到无效的语法错误@
    • 这是有道理的,因为我正在访问第一个索引 (c,'square') 但 [0,2] 运算符不仅仅考虑 numpy 数组,它正在将元组视为整个
    猜你喜欢
    • 2015-05-28
    • 2018-07-10
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多