I need to remove excessive duplicates of a particular element from the list, that is, if there's more than max_dup
duplicates of selected elements in a slice of the list, leave at most max_dup
elements in place. Obviously, stability (retaining order of elements in the list) is a must.
Example:
>>> remove_excessive_duplicates([1, '', '', '', 2, '', 3, '', '', '', '', '', 4, ''])
[1, '', '', 2, '', 3, '', '', 4, '']
The code I wrote:
def remove_excessive_duplicates(lst, dup='', max_dup=2):
new_lst = []
dcnt = 0
for elem in lst:
if elem == dup:
dcnt += 1
else:
dcnt = 0
if dcnt > max_dup:
continue
new_lst.append(elem)
return new_lst
It works, but I'm wondering if there's some cleverer way to do it, or the one that uses logic of some Python builtins to achieve the same goal.