Python按顺序返回列表中重复项的列表

问题描述 投票:0回答:1

您如何快速按照列表出现的顺序返回重复列表?例如,duplicates([2,3,5,5,5,6,6,3]) results in [5,6,3]表示重复的元素仅在其第二个元素出现时才添加到结果重复列表中。到目前为止,我有下面的代码,但是其运行速度不足以通过大型测试用例。有没有进口的更快的选择吗?

def duplicates(L):
    first = set()
    second = []
    for i in L:
        if i in first and i not in second:
            second.append(i)
            continue
        if i not in first and i not in second:
            first.add(i)
            continue
    return second
python list duplicates set repeat
1个回答
0
投票
依赖于字典中的键,对于Python 3.6+,该键由插入顺序排序(或可以使用OrderedDict)

Reference

代码

from collections import defaultdict def duplicates(lst): d = defaultdict(int) result = {} # Relies on dictionary keys tracking the order # items are added or can use Ordereddict for k in lst: d[k] += 1 if d[k] > 1: if k not in result: result[k] = None return list(result.keys()) lst = [2,3,5,5,5,6,6,3] print(duplicates(lst))

Out

[5, 6, 3]

0
投票
使用在添加订单项时报告字典键的事实

代码

from collections import defaultdict def duplicates(lst): d = defaultdict(int) result = {} # Relies ondictionary keys tracking the order # items are added or can use Ordereddict for k in lst: d[k] += 1 if d[k] > 1: if k not in result: result[k] = None return list(result.keys()) lst = [2,3,5,5,5,6,6,3] print(duplicates(lst))

Out

[5, 6, 3]
© www.soinside.com 2019 - 2024. All rights reserved.