如果你只是想从列表中删除第一n
发生的事情,这是很容易做到与发电机:
def remove_n_dupes(remove_from, what, how_many):
count = 0
for item in remove_from:
if item == what and count < how_many:
count += 1
else:
yield item
用法是这样的:
lst = [1,2,3,4,4,4,4,4]
print list(remove_n_dupes(lst, 4, 3)) # [1, 2, 3, 4, 4]
保持一个任何项目的指定重复项目是类似容易,如果我们使用一点额外的辅助存储:
from collections import Counter
def keep_n_dupes(remove_from, how_many):
counts = Counter()
for item in remove_from:
counts[item] += 1
if counts[item] <= how_many:
yield item
用法是相似的:
lst = [1,1,1,1,2,3,4,4,4,4,4]
print list(keep_n_dupes(lst, 2)) # [1, 1, 2, 3, 4, 4]
这里输入列表,并要保持项目的最大数量。需要注意的是,这些物品需要可排除...
@ dot.Py:绝对不是重复的,因为我们只是试图从列表中删除有限数量的项目,而不是完全消除重复项目。 – user2357112
你想删除'n'重复?或者断言任何给定项目至多有“m”个副本? – mgilson
另外,重要的是你删除了哪一个? (例如,你可以删除_first_4模糊,还是最后4个模板?) – mgilson