我有以下代碼。它正在工作,除非我有重複3次或更多次的重複,程序會將該元素視爲新號碼並顯示兩次。如何解決這個問題?顯示重複項和重複項數
import collections
mylist = [1,2,3,4,5,5,6,7,7,7,8,9]
i = 0
count = 0
for i in range(len(mylist)):
print1 = mylist.count(mylist[i])
if print1 > 1:
print("Duplicate Element: " , mylist[i])
print("It is repeated " , print1, "times")
mylist.remove(mylist[i])
count += 1
i += 1
我得到的輸出是
Duplicate Element: 5
It is repeated 2 times
Duplicate Element: 7
It is repeated 3 times
Duplicate Element: 7
It is repeated 2 times
Traceback (most recent call last):
File "C:/Users/sanantha/Documents/Python/Lab6/task3.py", line 10, in <module>
print1 = mylist.count(mylist[i])
IndexError: list index out of range
如何解決這一問題?
不要在您循環播放內容的同時修改列表。 'mylist.remove'使得列表縮短,但是你仍然在循環播放原始長度。 –
可能的重複:http://stackoverflow.com/questions/30565759/get-unique-values-in-list-of-lists-in-python –