[英]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.