import numpy as np
# To test on larger array
mat = np.array(np.random.random_integers(0, 9, 1000 * 1000)).reshape(1000, 1000)
res = []
for a in mat:
# Take out the zeros
no_zeros = a[a!=0]
if len(no_zeros) > 1:
for i in range(len(no_zeros) - 1):
# Only append pairs of non-equal neighbours
if no_zeros[i] != no_zeros[i+1]:
res.append((no_zeros[i], no_zeros[i+1]))
这应该能起到作用,尽管无可否认,它不是最优雅的;我在一个1000x1000的随机整数矩阵上进行了测试,测试速度非常快(一秒钟多一点)。我不确定您是如何看待输出的,所以我把它放在一个名为res的列表中
相关问题 更多 >
编程相关推荐