我需要打印矩阵的坐标,其对应的行和列只有零
的例子:
3 3
1 0 0
0 0 0
1 0 0
在上面的例子中,
在坐标(1,1)处,行和颜色为零(0),这样我就需要打印所有行和颜色为零的冠状值。(像需要检查加形状)
我代码:
r,c=map(int,input().split())
l=[list(map(int,input().split())) for i in range(r)]
for i in range(len(l)):
for j in range(0,len(l[i])):
if sum(l[i])==0 and sum(l[j])==0:
print(i,j)
我的代码在上面提到的输入工作,但下面提到的输入不工作,为什么??
输入:
6 13
1 0 1 0 1 0 1 0 1 0 1 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 1 0 1 0 1 0 1 0 1 0
输出需要:
1 13
2 13
3 13
4 13
我输出:1 1
1 2
1 3
1 4
Traceback (most recent call last):
File "main.py", line 5, in <module>
if sum(l[i])==0 and sum(l[j])==0:
IndexError: list index out of range
我犯了什么错误?请帮帮我!!
根据您在表上的迭代方式,l[i]
确实会给您l的第i行,但l[j]
会给您表l的第j行,而您实际上想要的是l的第j列。
索引错误发生b/c你有更多的列比行,所以你最终试图访问第7行(而不是列),确实不存在
不是最有效的方法但是为了得到第j列你可以遍历每一行的l[x][j] x:sum(l[x][j] for x in range(len(l))])
即:
r,c=map(int,input().split())
l=[list(map(int,input().split())) for i in range(r)]
for i in range(len(l)):
for j in range(0,len(l[i])):
if sum(l[i])==0 and sum(l[x][j] for x in range(len(l)))==0:
print(i,j)
# Outputs:
1 12
2 12
3 12
4 12
上面的测试用例