Py学习  »  Python

如何在python中打印对应行和列为零的矩阵的坐标?

Heisenberg • 3 年前 • 1208 次点击  

我需要打印矩阵的坐标,其对应的行和列仅为零

例子:

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

我犯了什么错误?请帮帮我!!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133378
文章 [ 1 ]  |  最新文章 3 年前
lemonhead
Reply   •   1 楼
lemonhead    3 年前

根据您在表中的迭代方式, l[i] 确实会给你第i行的l,但是 l[j] 将给出表l的第j行,而实际上需要表l的第j列。

如果列多于行,则会出现索引错误,因此最终会尝试访问第7行 一行 (而不是专栏)这确实不存在

这不是最有效的方法,但要获得第j列,可以对每行x的每个l[x][j]进行迭代: 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

在上面的测试用例中