本文介紹了遍歷列表并刪除重復元素時出現循環問題的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想遍歷一個列表,并刪除多次計數的項目,這樣它們就不會被 for 循環重復打印.
I want to iterate through a list, and remove the items that count more than once, so they don't get printed repeatedly by the for loop.
但是,列表中僅出現一次的某些項目似乎也受此影響,我不知道為什么.
However, some items appearing only one time in the list seem to get affected too by this, and I can't figure out why.
任何意見將不勝感激.
示例輸出:
listy = [2,2,1,3,4,2,1,2,3,4,5]
for i in listy:
if listy.count(i)>1:
print i, listy.count(i)
while i in listy: listy.remove(i)
else:
print i, listy.count(i)
輸出:
2 4
3 2
1 2
因此完全忽略了 4 和 5.
thus ignoring completely 4 and 5.
推薦答案
您不應該在迭代列表時修改它.這個應該可以工作:
You should not modify a list while iterating over it. This one should work:
listy = [2,2,1,3,4,2,1,2,3,4,5]
found = set()
for i in listy:
if not i in found:
print i, listy.count(i)
found.add(i)
結果是:
2 4
1 2
3 2
4 2
5 1
這篇關于遍歷列表并刪除重復元素時出現循環問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!