Python-如何在列表中找到重复项并使用它们创建另一个列表?

发布于 2021-02-02 23:21:05

如何在Python列表中找到重复项并创建另一个重复项列表?该列表仅包含整数。

关注者
0
被浏览
136
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    要删除重复项,请使用set(a)。要打印副本,请执行以下操作:

    a = [1,2,3,2,1,5,6,5,5,5]
    
    import collections
    print([item for item, count in collections.Counter(a).items() if count > 1])
    
    ## [1, 2, 5]
    

    请注意,这Counter并不是特别有效(计时),并且在这里可能会过大。set会表现更好。此代码按源顺序计算唯一元素的列表:

    seen = set()
    uniq = []
    for x in a:
        if x not in seen:
            uniq.append(x)
            seen.add(x)
    

    或者,更简洁地说:

    seen = set()
    uniq = [x for x in a if x not in seen and not seen.add(x)]    
    

    我不建议你使用后一种样式,因为not seen.add(x)这样做并不明显(set add()方法始终返回None,因此需要not)。

    要计算没有库的重复元素列表:

    seen = {}
    dupes = []
    
    for x in a:
        if x not in seen:
            seen[x] = 1
        else:
            if seen[x] == 1:
                dupes.append(x)
            seen[x] += 1
    

    如果列表元素不可散列,则不能使用集合/字典,而必须求助于二​​次时间解(将每个解比较)。例如:

    a = [[1], [2], [3], [1], [5], [3]]
    
    no_dupes = [x for n, x in enumerate(a) if x not in a[:n]]
    print no_dupes # [[1], [2], [3], [5]]
    
    dupes = [x for n, x in enumerate(a) if x in a[:n]]
    print dupes # [[1], [3]]
    


  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。
    >>> l = [1,2,3,4,4,5,5,6,1]
    >>> set([x for x in l if l.count(x) > 1])
    set([1, 4, 5])
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看