所以我有一個包含整數的串列串列,我想回傳其中有多少行/串列有數字 5 和 8 出現兩次以上。我撰寫了以下代碼,這對我來說在邏輯上是有意義的,但它回傳 0。任何幫助將不勝感激。
我正在尋找的輸出是 3,因為串列 0,2 和 5 的數字 5 和 8 出現了兩次以上。
five_count = 0
eight_count = 0
row_count = 0
test =[[5,0,5,0,0,0,8,0,8,0,0],
[1,1,5,98,5,5,13,13,6,7,8],
[5,0,5,0,0,0,8,0,8,0,0],
[1,1,5,5,56,5,13,13,6,7,8],
[1,9,5,5,25,5,13,19,6,7,8],
[5,0,5,0,0,0,8,0,8,0,0]
]
for list in test:
for num in list:
if(num == 5):
five_count= 1
elif(num == 8):
eight_count= 1
if(five_count >= 2 and eight_count >= 2):
row_count= 1
print(row_count)
uj5u.com熱心網友回復:
您可以使用串列理解和list.count(num)回傳 no 的函式。次num發生在list-
test =[[5,0,5,0,0,0,8,0,8,0,0],
[1,1,5,98,5,5,13,13,6,7,8],
[5,0,5,0,0,0,8,0,8,0,0],
[1,1,5,5,56,5,13,13,6,7,8],
[1,9,5,5,25,5,13,19,6,7,8],
[5,0,5,0,0,0,8,0,8,0,0]
]
# if your are interested in only the count of rows
row_count = sum(1 for l in test if l.count(5) >= 2 and l.count(8) >= 2)
print(row_count) # prints 3
# if you want all the indexes where the condition is satisfied
indexes = [ind for ind, l in enumerate(test) if l.count(5) >= 2 and l.count(8) >= 2]
print(indexes) # prints [0, 2, 5]
修改你的代碼,注意
- 用of
=代替不正確= - 的縮進
if (five_count >= 2 and eight_count >= 2) - 為每個串列設定
five_countandeight_count,0以便我們從0-重新開始計數
test =[[5,0,5,0,0,0,8,0,8,0,0],
[1,1,5,98,5,5,13,13,6,7,8],
[5,0,5,0,0,0,8,0,8,0,0],
[1,1,5,5,56,5,13,13,6,7,8],
[1,9,5,5,25,5,13,19,6,7,8],
[5,0,5,0,0,0,8,0,8,0,0]
]
row_count = 0
for list in test:
five_count, eight_count = 0, 0
for num in list:
if (num == 5):
five_count = 1
elif (num == 8):
eight_count = 1
print(five_count, eight_count)
if (five_count >= 2 and eight_count >= 2):
row_count = 1
print(row_count) # prints 3
uj5u.com熱心網友回復:
問題是當您更新計數器時。
five_count = 1
無論如何,將計數器設定為 1。您需要的正確語法是
five_count = 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/427607.html
上一篇:如何只為串列中的y坐標添加值?
