我有以下代码。它正在工作,除非我有一个重复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
如何解决这个问题?
答案 0 :(得分:0)
以下是使用itertools.groupby
:
from itertools import groupby
print(*["Duplicate element: {}. It is repeated {} times."
.format(k, len(list(group))) for k, group in groupby(mylist)
if len(list(group)) > 1],
sep='\n')
输出:
Duplicate element: 5. It is repeated 2 times.
Duplicate element: 7. It is repeated 3 times.
答案 1 :(得分:0)
使用collections.Counter,它是为此而构建的:
from collections import Counter
mylist = [1,2,3,4,5,5,6,7,7,7,8,9]
for value, repeats in Counter(mylist).items():
if repeats > 1:
print("Value {} repeats {} times".format(value, repeats)
答案 2 :(得分:0)
您的代码只需要修复。这种方式的最佳方法是使用sets
mylist = [1,2,3,4,5,5,6,7,7,7,8,9]
for i in set(mylist):
count = mylist.count(i)
if count > 1:
print('Duplicate Element: %i' % i)
print('It is repeated %i times' % count)
答案 3 :(得分:0)
索引超出范围意味着您正在尝试访问数据结构中超出范围的元素。
E.g。你有一个数组[1,2,3,4](索引:0,1,2,3) - 你在索引1上执行删除。 这将给你一个[1,3,4]数组(索引:0,1,2)。现在尝试访问索引3将导致索引超出范围异常,因为它不再存在。