[英]Removing some of the duplicates from a list in Python
我想刪除列表中的一定數量的重復項而不刪除所有列表。 例如,我有一個列表[1,2,3,4,4,4,4,4]
,我想刪除4個中的3個,所以我留下[1,2,3,4,4]
。 一個天真的方式可能會這樣做
def remove_n_duplicates(remove_from, what, how_many):
for j in range(how_many):
remove_from.remove(what)
有沒有辦法在列表的一次通過中刪除三個4,但保留另外兩個。
如果您只想從列表中刪除前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]
此處輸入是您要保留的列表和最大項目數。 需要注意的是,這些物品需要可以清洗......
您可以使用Python的set功能和&運算符來創建列表列表,然后展平列表。 結果列表將是[1,2,3,4,4]。
x = [1,2,3,4,4,4,4,4]
x2 = [val for sublist in [[item]*max(1, x.count(item)-3) for item in set(x) & set(x)] for val in sublist]
作為一項功能,您將擁有以下內容。
def remove_n_duplicates(remove_from, what, how_many):
return [val for sublist in [[item]*max(1, remove_from.count(item)-how_many) if item == what else [item]*remove_from.count(item) for item in set(remove_from) & set(remove_from)] for val in sublist]
如果列表已排序,則有快速解決方案:
def remove_n_duplicates(remove_from, what, how_many):
index = 0
for i in range(len(remove_from)):
if remove_from[i] == what:
index = i
break
if index + how_many >= len(remove_from):
#There aren't enough things to remove.
return
for i in range(index, how_many):
if remove_from[i] != what:
#Again, there aren't enough things to remove
return
endIndex = index + how_many
return remove_from[:index+1] + remove_from[endIndex:]
請注意,這將返回新數組,因此您要執行arr = removeCount(arr,4,3)
我可以使用集合以不同的方式解決它。
from collections import Counter
li = [1,2,3,4,4,4,4]
cntLi = Counter(li)
print cntLi.keys()
這是另一個有時可能有用的技巧。 不作為推薦配方。
def remove_n_duplicates(remove_from, what, how_many):
exec('remove_from.remove(what);'*how_many)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.