如何在整数列表中找到重复项并创建重复项的另一个列表?


当前回答

这里有很多答案,但我认为这是一个相对易于阅读和理解的方法:

def get_duplicates(sorted_list):
    duplicates = []
    last = sorted_list[0]
    for x in sorted_list[1:]:
        if x == last:
            duplicates.append(x)
        last = x
    return set(duplicates)

注:

如果您希望保留重复计数,请去掉强制转换 'set'在底部获得完整的列表 如果您更喜欢使用生成器,请将duplicate .append(x)替换为yield x和底部的return语句(您可以稍后强制转换为set)

其他回答

some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
some_dictionary = {}

for element in some_list:
    if element not in some_dictionary:
       some_dictionary[element] = 1
    else:
        some_dictionary[element] += 1

for key, value in some_dictionary.items():
    if value > 1:
       print(key, end = ' ')

# another way
duplicates = []

for x in some_list:
    if some_list.count(x) > 1 and x not in duplicates:
        duplicates.append(x)

print()
print(duplicates)

来源:这里

我没有看到一个纯粹使用迭代器的解决方案,所以我们开始吧

这需要对列表进行排序,这可能是这里的缺点。

a = [1,2,3,2,1,5,6,5,5,5]
a.sort()
set(map(lambda x: x[0], filter(lambda x: x[0] == x[1], zip(a, a[1:]))))

{1, 2, 5}

你可以用这段代码轻松检查你的机器有多快,有一百万潜在的重复:

首先生成数据

import random
from itertools import chain
a = list(chain(*[[n] * random.randint(1, 2) for n in range(1000000)]))

并运行测试:

set(map(lambda x: x[0], filter(lambda x: x[0] == x[1], zip(a, a[1:]))))

不用说,这个解决方案只在列表已经排序的情况下才有效。

为了好玩,只需要一行语句。

(lambda iterable: reduce(lambda (uniq, dup), item: (uniq, dup | {item}) if item in uniq else (uniq | {item}, dup), iterable, (set(), set())))(some_iterable)

使用sort()函数。重复项可以通过遍历它并检查l1[i] == l1[i+1]来识别。

raw_list = [1,2,3,3,4,5,6,6,7,2,3,4,2,3,4,1,3,4,]

clean_list = list(set(raw_list))
duplicated_items = []

for item in raw_list:
    try:
        clean_list.remove(item)
    except ValueError:
        duplicated_items.append(item)


print(duplicated_items)
# [3, 6, 2, 3, 4, 2, 3, 4, 1, 3, 4]

基本上可以通过转换为set (clean_list)来删除重复项,然后迭代raw_list,同时删除出现在raw_list中的clean列表中的每个项。如果item未找到,则捕获引发的ValueError异常,并将该item添加到duplicated_items列表中。

如果需要重复项的索引,只需枚举列表并使用索引即可。(对于index, item in enumerate(raw_list):),对于大型列表(比如上千+的元素)来说,这是更快和优化的