python - 如果数字为 1,如何按值检查矩阵值

标签 python matrix

我想检查矩阵中的所有值,如果是 1,则打印 x,y 坐标。

这是我的矩阵:

0, 0, 0, 1,
1, 0, 0, 0,
0, 0, 1, 0,
0, 1, 0, 0,

到目前为止,这是我的代码:

m = open('matrix.txt', 'r')
l = []
l = [line.split() for line in m]
for x in range(4):
    for y in range(4):
        p = int(l[x][y][:-1])
        if p == 1:
            print(x, y)

但是当我运行它时,我得到了这个:

坐标:

0 3
1 0
2 2
3 1

然后是这个错误:

ValueError: invalid literal for int() with base 10: ''

我做错了什么?

最佳答案

或者我会建议使用 numpy 来处理矩阵。

下面是如何使用 argwhere 来实现:

In [6]: import numpy as np

In [7]: m = np.matrix([
[0, 0, 0, 1],
[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0]])

# use argwhere to find the coordinates
In [8]: np.argwhere(m == 1)
Out[8]:
array([[[0, 3]],

       [[1, 0]],

       [[2, 2]],

       [[3, 1]]])

以元组列表的形式返回:

In [10]: list(map(tuple, np.argwhere(m == 1)))
Out[10]: [(0, 3), (1, 0), (2, 2), (3, 1)]

要构建矩阵,您可以使用:

m = np.matrix([map(int, filter(lambda x: x, line.strip().split(","))) 
               for line in f]) # where f is your opened file

希望这对您有所帮助。

关于python - 如果数字为 1,如何按值检查矩阵值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32243499/

相关文章:

Python:排序函数的参数

c++ - 读取包含矩阵 C++ 的文本文件

c++ - 如何正确初始化、分配和使用动态特征矩阵作为 C++ 中的类成员?

r - 是否有一个 R 包可以从频率表中计算一阶转换矩阵?

r - 具有 0 值的 R 矩阵单元格需要多少空间?以及如何处理大矩阵计算

替换 R 中的矩阵列

python - 使用基于类的 View 提交表单集数据

python - 在 Python 中创建流类

python - 如何将列表转换为以逗号分隔的字符串?

python 周期性循环成语?