繁体   English   中英

从Python中的列表中删除一些重复项

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM