求矩阵中满足相邻条件的所有数对

2024-04-26 08:13:30 发布

您现在位置:Python中文网/ 问答频道 /正文

假设你有一个矩阵:

import numpy as np
mat = np.array([[0, 0, 1], [2, 0, 1], [1, 0, 3]])

你要检索这个矩阵中所有相邻的数字对,不相等,忽略零。在这种情况下,这将是3&;1和2&;但是我想把这个应用到一个非常大的矩阵。非常感谢您的帮助,谢谢


Tags: importnumpyasnp情况矩阵数字array
1条回答
网友
1楼 · 发布于 2024-04-26 08:13:30

这应该能起到作用,尽管无可否认,它不是最优雅的;我在一个1000x1000的随机整数矩阵上进行了测试,测试速度非常快(一秒钟多一点)。我不确定您是如何看待输出的,所以我把它放在一个名为res的列表中

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]))

相关问题 更多 >