【问题标题】:return duplicates in a list [duplicate]返回列表中的重复项[重复]
【发布时间】:2015-10-04 17:14:44
【问题描述】:

此函数采用未排序值的整数列表(您的函数不得修改),并返回第一个列表中所有重复项的排序列表。例如,duplicates([1, 3, 5, 7, 9, 5, 3, 5, 3]) 将返回 [3, 5]。如果没有重复,则返回一个空列表。

以下是我当前的代码,它不起作用。我该如何解决这个问题?

def FindDuplicates(in_list):  
    unique = set(in_list)  
    for each in unique:  
        count = in_list.count(each)  
        if count > 1:  
            print count  
            return True  
    print []  
    return False

【问题讨论】:

标签: python list count


【解决方案1】:

要在没有 Counter/dict 的情况下执行此操作,您可以修改当前代码以将重复值保存在新列表中,如下所示:

def FindDuplicates(in_list):  
    duplicates = []
    unique = set(in_list)
    for each in unique:
        count = in_list.count(each)
        if count > 1:
            duplicates.append(each)
    print duplicates

将输出:

>>> FindDuplicates(lst)
[3, 5]

如果您需要排序结果,请在末尾使用sorted(duplicates) 调用以获取按值排序的结果。


您也可以使用collections.Counter 和列表推导来解决此问题(即在列表中查找重复项),如下所示:

>>> from collections import Counter
>>> lst = [1, 3, 5, 7, 9, 5, 3, 5, 3]
>>> def duplicates(list_of_numbers):
...    counter = Counter(list_of_numbers)
...    return [y for y in counter if counter[y] > 1]
... 
>>> duplicates(lst)
[3, 5]

上述解决方案假定列表的元素是可散列的。

【讨论】:

  • 你确定这回答了 OP 的问题吗?因为目前还没有...
  • 非常感谢,但是我以前用过counter,老师说不能用。没有柜台有什么办法吗?
  • 我认为您还需要致电sorted,因为计数器是任意顺序的?
  • @NightShadeQueen 不,如果使用sorted,订单不一定会恢复。 dicts 不维护键的顺序,也不能保证原始列表是排序的。
  • @Aleish 检查编辑...,我已经编辑了您当前的代码。这是 O(N^2) 的非最优解,但不确定您是否也可以使用 dicts。
【解决方案2】:

在 O(nlogn) 最坏情况下稍快

def FindDuplicates(in_list):  
    unique = set()
    duplicates = set()
    for i in in_list:
        if i in unique: #hey, I've seen you before
            duplicates.add(i)
        else:
            unique.add(i)
    return sorted(duplicates) 
    #It's this call to sorted that makes it O(nlogn)
    #without it, it'd be O(n)

还有“伙计,你不能阻止我使用计数器!”变体。也是 O(nlogn)。

def FindDuplicates(in_list):
    d = {}
    for i in in_list:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return sorted(i for i,j in d.items() if j > 1)
   #python2 use d.iteritems() not d.items()

(我想

if i not in d:
    d[i] = 1
else:
    d[i] += 1

对大多数人来说更有意义,而且它也会起作用。)

【讨论】:

  • 如果你删除排序的调用,两个解决方案都变成 O(n)。这里真的需要排序吗?
  • 来自问题:“返回第一个列表中所有重复项的排序列表”所以,是的。
  • 啊,在阅读问题时完全错过了这一点。现在也了解您对我的回答的评论。 +1。
猜你喜欢
  • 2014-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-22
  • 1970-01-01
  • 2018-06-25
相关资源
最近更新 更多