# 如何使用类似布尔型的方形对称numpy数组中的True值存储存储索引对？

``````import numpy as np
array = np.array([
[0, 0, 1, 0, 1, 0, 1],
[0, 0, 1, 1, 0, 1, 0],
[1, 1, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 1, 1, 0],
[1, 0, 0, 1, 0, 0, 1],
[0, 1, 0, 1, 0, 0, 0],
[1, 0, 1, 0, 1, 0, 0]
])
``````

``````[
[0, 2],
[0, 4],
[0, 6],
[1, 2],
[1, 3],
[1, 5],
[2, 6],
[3, 4],
[3, 5],
[4, 6]
]
``````

``````result = []
for i in range(array.shape[0]):
for j in range(i):
if array[i][j]:
result.append([i, j])
print(pd.DataFrame(result).sort_values(1).values)

# using dataframes and arrays for formatting but looking for
# 'result' which is a list

# Returns (same as above but columns are the opposite way round):
[[2 0]
[4 0]
[6 0]
[2 1]
[3 1]
[5 1]
[6 2]
[4 3]
[5 3]
[6 4]]
``````

``````idx = np.argwhere(array)
idx = idx[idx[:,0]<idx[:,1]]
``````

``````idx = np.argwhere(np.triu(array))
``````

``````[[0 2]
[0 4]
[0 6]
[1 2]
[1 3]
[1 5]
[2 6]
[3 4]
[3 5]
[4 6]]
``````

``````#@bousof solution
def method1(array):
return np.vstack(np.where(np.logical_and(array, np.diff(np.ogrid[:array.shape[0],:array.shape[0]])[0]>=0))).transpose()[:,::-1]

#Also mentioned by @hpaulj
def method2(array):
return np.argwhere(np.triu(array))

def method3(array):
idx = np.argwhere(array)
return idx[idx[:,0]<idx[:,1]]

#The original method in question by OP(d-man)
def method4(array):
result = []
for i in range(array.shape[0]):
for j in range(i):
if array[i][j]:
result.append([i, j])
return result

def method5(array):
return np.vstack(np.where(np.triu(array))).transpose()

inputs = [np.random.randint(0,2,(n,n)) for n in [10,100,1000,10000]]
``````

0条评论