我需要列印相應行和列僅為零的矩陣的坐標
例子:
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
我犯了什么錯誤?請幫我!!
uj5u.com熱心網友回復:
根據您在表上的迭代方式,l[i]確實會給您 l 的第 i 行,但l[j]會給您表 l 的第 j 行,而您實際上想要 l 的第 j 列。
索引錯誤發生在 b/c 您的列多于行,因此您最終嘗試訪問確實不存在的第 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
在上面的測驗用例上
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/469361.html
標籤:Python python-3.x
