我想检查矩阵中的所有值,如果是 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/