如果你只是想從列表中刪除第一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