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

MFB*_*MFB 397 python list duplicates

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

geo*_*org 494

删除重复使用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]
Run Code Online (Sandbox Code Playgroud)

请注意,这Counter不是特别有效(时间),可能在这里有点过分.set会表现得更好.此代码计算源顺序中的唯一元素列表:

seen = set()
uniq = []
for x in a:
    if x not in seen:
        uniq.append(x)
        seen.add(x)
Run Code Online (Sandbox Code Playgroud)

或者,更简洁地说:

seen = set()
uniq = [x for x in a if x not in seen and not seen.add(x)]    
Run Code Online (Sandbox Code Playgroud)

我不推荐后一种风格,因为它不明显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
Run Code Online (Sandbox Code Playgroud)

如果列表元素不可清除,则不能使用集合/ dicts并且必须求助于二​​次时间解决方案(将每个解析比较每个).例如:

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]]
Run Code Online (Sandbox Code Playgroud)

  • 将您对set()的答案转换为仅获取重复项。`seen = set()`然后`dupe = set(x如果在x中看到x则为x的x.add(x))` (4认同)
  • @Hugo,要查看重复列表,我们只需要创建一个名为dup的新列表并添加else语句.例如:`dup = []``else:dup.append(x)` (3认同)
  • @oxeimon:您可能已经知道了,但是您在python 3`print()`中用圆括号调用了print (3认同)
  • 对于 Python 3.x: print ([item for item, count in collections.Counter(a).items() if count > 1]) (3认同)
  • @eric:我猜它是'O(n)`,因为它只迭代列表一次并且设置查找是'O(1)`. (2认同)
  • 我注意到在没有库的情况下查找重复元素的代码存在问题。`if saw[x] == 1:` 应更改为 `if saw[x] >= 1:`。就像现在一样,第二次出现重复项后的重复项将被忽略。 (2认同)

小智 302

>>> 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])
Run Code Online (Sandbox Code Playgroud)

  • 实际上,这是一个简单的解决方案,但复杂性是平方的,因为每个count()都会再次解析列表,所以不要用于大型列表. (56认同)
  • @JohnJ,冒泡排序也很简单而有效.这并不意味着我们应该使用它! (4认同)
  • 不要这样做。 (3认同)
  • 你有没有理由使用列表理解而不是生成器理解? (2认同)

moo*_*eep 77

您不需要计数,只需要查看之前是否看过该项目.改编了这个问题的答案:

def list_duplicates(seq):
  seen = set()
  seen_add = seen.add
  # adds all elements it doesn't know yet to seen and all other to seen_twice
  seen_twice = set( x for x in seq if x in seen or seen_add(x) )
  # turn the set into a list (as requested)
  return list( seen_twice )

a = [1,2,3,2,1,5,6,5,5,5]
list_duplicates(a) # yields [1, 2, 5]
Run Code Online (Sandbox Code Playgroud)

为了防止速度问题,这里有一些时间:

# file: test.py
import collections

def thg435(l):
    return [x for x, y in collections.Counter(l).items() if y > 1]

def moooeeeep(l):
    seen = set()
    seen_add = seen.add
    # adds all elements it doesn't know yet to seen and all other to seen_twice
    seen_twice = set( x for x in l if x in seen or seen_add(x) )
    # turn the set into a list (as requested)
    return list( seen_twice )

def RiteshKumar(l):
    return list(set([x for x in l if l.count(x) > 1]))

def JohnLaRooy(L):
    seen = set()
    seen2 = set()
    seen_add = seen.add
    seen2_add = seen2.add
    for item in L:
        if item in seen:
            seen2_add(item)
        else:
            seen_add(item)
    return list(seen2)

l = [1,2,3,2,1,5,6,5,5,5]*100
Run Code Online (Sandbox Code Playgroud)

以下是结果:(做得好@JohnLaRooy!)

$ python -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
10000 loops, best of 3: 74.6 usec per loop
$ python -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
10000 loops, best of 3: 91.3 usec per loop
$ python -mtimeit -s 'import test' 'test.thg435(test.l)'
1000 loops, best of 3: 266 usec per loop
$ python -mtimeit -s 'import test' 'test.RiteshKumar(test.l)'
100 loops, best of 3: 8.35 msec per loop
Run Code Online (Sandbox Code Playgroud)

有趣的是,除了时间本身,当使用pypy时,排名也略有变化.最有趣的是,基于计数器的方法从pypy的优化中获益匪浅,而我建议的方法缓存方法似乎几乎没有效果.

$ pypy -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
100000 loops, best of 3: 17.8 usec per loop
$ pypy -mtimeit -s 'import test' 'test.thg435(test.l)'
10000 loops, best of 3: 23 usec per loop
$ pypy -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
10000 loops, best of 3: 39.3 usec per loop
Run Code Online (Sandbox Code Playgroud)

显然,这种效果与输入数据的"重复性"有关.我已经设定l = [random.randrange(1000000) for i in xrange(10000)]并得到了这些结果:

$ pypy -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
1000 loops, best of 3: 495 usec per loop
$ pypy -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
1000 loops, best of 3: 499 usec per loop
$ pypy -mtimeit -s 'import test' 'test.thg435(test.l)'
1000 loops, best of 3: 1.68 msec per loop
Run Code Online (Sandbox Code Playgroud)

  • 只是好奇 - 这里有see_add = seen.add的目的是什么? (6认同)
  • @Rob这样你就可以调用之前查过的函数.否则,每次需要插入时,您需要查找(字典查询)成员函数`add`. (3认同)

F1R*_*ors 29

我在查看相关内容时遇到了这个问题 - 并想知道为什么没有人提供基于发电机的解决方案?解决这个问题将是:

>>> print list(getDupes_9([1,2,3,2,1,5,6,5,5,5]))
[1, 2, 5]
Run Code Online (Sandbox Code Playgroud)

我关注可扩展性,因此测试了几种方法,包括在小型列表上运行良好的天真项目,但随着列表变得更大而规模可怕(注意 - 使用timeit会更好,但这是说明性的).

我将@moooeeeep包括在内进行比较(它的速度非常快:如果输入列表完全是随机的,速度最快)和迭代工具,对于大多数排序列表来说再次更快......现在包括来自@firelynx的pandas方法 - 慢,但不是可怕的,简单的.注意 - 排序/开球/拉链方法在我的机器上对于大多数有序列表而言始终是最快的,对于洗牌列表来说moooeeeep是最快的,但您的里程可能会有所不同.

好处

  • 使用相同的代码非常快速地测试"任何"重复项

假设

  • 重复项应仅报告一次
  • 不需要保留重复的顺序
  • 重复可能在列表中的任何位置

最快的解决方案,1米条目:

def getDupes(c):
        '''sort/tee/izip'''
        a, b = itertools.tee(sorted(c))
        next(b, None)
        r = None
        for k, g in itertools.izip(a, b):
            if k != g: continue
            if k != r:
                yield k
                r = k
Run Code Online (Sandbox Code Playgroud)

测试方法

import itertools
import time
import random

def getDupes_1(c):
    '''naive'''
    for i in xrange(0, len(c)):
        if c[i] in c[:i]:
            yield c[i]

def getDupes_2(c):
    '''set len change'''
    s = set()
    for i in c:
        l = len(s)
        s.add(i)
        if len(s) == l:
            yield i

def getDupes_3(c):
    '''in dict'''
    d = {}
    for i in c:
        if i in d:
            if d[i]:
                yield i
                d[i] = False
        else:
            d[i] = True

def getDupes_4(c):
    '''in set'''
    s,r = set(),set()
    for i in c:
        if i not in s:
            s.add(i)
        elif i not in r:
            r.add(i)
            yield i

def getDupes_5(c):
    '''sort/adjacent'''
    c = sorted(c)
    r = None
    for i in xrange(1, len(c)):
        if c[i] == c[i - 1]:
            if c[i] != r:
                yield c[i]
                r = c[i]

def getDupes_6(c):
    '''sort/groupby'''
    def multiple(x):
        try:
            x.next()
            x.next()
            return True
        except:
            return False
    for k, g in itertools.ifilter(lambda x: multiple(x[1]), itertools.groupby(sorted(c))):
        yield k

def getDupes_7(c):
    '''sort/zip'''
    c = sorted(c)
    r = None
    for k, g in zip(c[:-1],c[1:]):
        if k == g:
            if k != r:
                yield k
                r = k

def getDupes_8(c):
    '''sort/izip'''
    c = sorted(c)
    r = None
    for k, g in itertools.izip(c[:-1],c[1:]):
        if k == g:
            if k != r:
                yield k
                r = k

def getDupes_9(c):
    '''sort/tee/izip'''
    a, b = itertools.tee(sorted(c))
    next(b, None)
    r = None
    for k, g in itertools.izip(a, b):
        if k != g: continue
        if k != r:
            yield k
            r = k

def getDupes_a(l):
    '''moooeeeep'''
    seen = set()
    seen_add = seen.add
    # adds all elements it doesn't know yet to seen and all other to seen_twice
    for x in l:
        if x in seen or seen_add(x):
            yield x

def getDupes_b(x):
    '''iter*/sorted'''
    x = sorted(x)
    def _matches():
        for k,g in itertools.izip(x[:-1],x[1:]):
            if k == g:
                yield k
    for k, n in itertools.groupby(_matches()):
        yield k

def getDupes_c(a):
    '''pandas'''
    import pandas as pd
    vc = pd.Series(a).value_counts()
    i = vc[vc > 1].index
    for _ in i:
        yield _

def hasDupes(fn,c):
    try:
        if fn(c).next(): return True    # Found a dupe
    except StopIteration:
        pass
    return False

def getDupes(fn,c):
    return list(fn(c))

STABLE = True
if STABLE:
    print 'Finding FIRST then ALL duplicates, single dupe of "nth" placed element in 1m element array'
else:
    print 'Finding FIRST then ALL duplicates, single dupe of "n" included in randomised 1m element array'
for location in (50,250000,500000,750000,999999):
    for test in (getDupes_2, getDupes_3, getDupes_4, getDupes_5, getDupes_6,
                 getDupes_8, getDupes_9, getDupes_a, getDupes_b, getDupes_c):
        print 'Test %-15s:%10d - '%(test.__doc__ or test.__name__,location),
        deltas = []
        for FIRST in (True,False):
            for i in xrange(0, 5):
                c = range(0,1000000)
                if STABLE:
                    c[0] = location
                else:
                    c.append(location)
                    random.shuffle(c)
                start = time.time()
                if FIRST:
                    print '.' if location == test(c).next() else '!',
                else:
                    print '.' if [location] == list(test(c)) else '!',
                deltas.append(time.time()-start)
            print ' -- %0.3f  '%(sum(deltas)/len(deltas)),
        print
    print
Run Code Online (Sandbox Code Playgroud)

'all dupes'测试的结果是一致的,在这个数组中发现"第一个"重复然后"全部"重复:

Finding FIRST then ALL duplicates, single dupe of "nth" placed element in 1m element array
Test set len change :    500000 -  . . . . .  -- 0.264   . . . . .  -- 0.402  
Test in dict        :    500000 -  . . . . .  -- 0.163   . . . . .  -- 0.250  
Test in set         :    500000 -  . . . . .  -- 0.163   . . . . .  -- 0.249  
Test sort/adjacent  :    500000 -  . . . . .  -- 0.159   . . . . .  -- 0.229  
Test sort/groupby   :    500000 -  . . . . .  -- 0.860   . . . . .  -- 1.286  
Test sort/izip      :    500000 -  . . . . .  -- 0.165   . . . . .  -- 0.229  
Test sort/tee/izip  :    500000 -  . . . . .  -- 0.145   . . . . .  -- 0.206  *
Test moooeeeep      :    500000 -  . . . . .  -- 0.149   . . . . .  -- 0.232  
Test iter*/sorted   :    500000 -  . . . . .  -- 0.160   . . . . .  -- 0.221  
Test pandas         :    500000 -  . . . . .  -- 0.493   . . . . .  -- 0.499  
Run Code Online (Sandbox Code Playgroud)

当列表首先被洗牌时,排序的价格变得明显 - 效率明显下降并且@moooeeeep方法占主导地位,set和dict方法相似但是表现不佳:

Finding FIRST then ALL duplicates, single dupe of "n" included in randomised 1m element array
Test set len change :    500000 -  . . . . .  -- 0.321   . . . . .  -- 0.473  
Test in dict        :    500000 -  . . . . .  -- 0.285   . . . . .  -- 0.360  
Test in set         :    500000 -  . . . . .  -- 0.309   . . . . .  -- 0.365  
Test sort/adjacent  :    500000 -  . . . . .  -- 0.756   . . . . .  -- 0.823  
Test sort/groupby   :    500000 -  . . . . .  -- 1.459   . . . . .  -- 1.896  
Test sort/izip      :    500000 -  . . . . .  -- 0.786   . . . . .  -- 0.845  
Test sort/tee/izip  :    500000 -  . . . . .  -- 0.743   . . . . .  -- 0.804  
Test moooeeeep      :    500000 -  . . . . .  -- 0.234   . . . . .  -- 0.311  *
Test iter*/sorted   :    500000 -  . . . . .  -- 0.776   . . . . .  -- 0.840  
Test pandas         :    500000 -  . . . . .  -- 0.539   . . . . .  -- 0.540  
Run Code Online (Sandbox Code Playgroud)

  • 这个答案非常好。我不明白它没有更多的解释和测试点,这对于那些需要它的人来说非常有用。 (2认同)
  • `itertools.tee` 增加了不必要的开销。尝试使用“c = Sorted(c)”,然后使用“a, b = iter(c), iter(c)”。 (2认同)

MSe*_*ert 28

你可以使用iteration_utilities.duplicates:

>>> from iteration_utilities import duplicates

>>> list(duplicates([1,1,2,1,2,3,4,2]))
[1, 1, 2, 2]
Run Code Online (Sandbox Code Playgroud)

或者如果您只想要每个副本中的一个,则可以将其与iteration_utilities.unique_everseen以下内容结合使

>>> from iteration_utilities import unique_everseen

>>> list(unique_everseen(duplicates([1,1,2,1,2,3,4,2])))
[1, 2]
Run Code Online (Sandbox Code Playgroud)

它还可以处理不可用的元素(但是以性能为代价):

>>> list(duplicates([[1], [2], [1], [3], [1]]))
[[1], [1]]

>>> list(unique_everseen(duplicates([[1], [2], [1], [3], [1]])))
[[1]]
Run Code Online (Sandbox Code Playgroud)

这是其中只有少数其他方法可以处理的东西.

基准

我做了一个包含大多数(但不是全部)这里提到的方法的快速基准测试.

第一个基准仅包括一小部分列表长度,因为某些方法具有O(n**2)行为.

在图中,y轴表示时间,因此较低的值表示更好.它还绘制了log-log,因此可以更好地显示各种值:

在此输入图像描述

删除O(n**2)方法我在列表中做了另外50个元素的基准测试:

在此输入图像描述

正如您所看到的,该iteration_utilities.duplicates方法比任何其他方法unique_everseen(duplicates(...))都快,甚至链接比其他方法更快或更快.

另外一个值得注意的有趣的事情是,对于小型列表而言,大熊猫方法非常慢,但很容易竞争更长的列表.

然而,由于这些基准测试显示大多数方法的执行大致相同,因此使用哪一个并不重要(除了具有O(n**2)运行时的3个).

from iteration_utilities import duplicates, unique_everseen
from collections import Counter
import pandas as pd
import itertools

def georg_counter(it):
    return [item for item, count in Counter(it).items() if count > 1]

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

def georg_set2(it):
    seen = set()
    return [x for x in it if x not in seen and not seen.add(x)]   

def georg_set3(it):
    seen = {}
    dupes = []

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

def RiteshKumar_count(l):
    return set([x for x in l if l.count(x) > 1])

def moooeeeep(seq):
    seen = set()
    seen_add = seen.add
    # adds all elements it doesn't know yet to seen and all other to seen_twice
    seen_twice = set( x for x in seq if x in seen or seen_add(x) )
    # turn the set into a list (as requested)
    return list( seen_twice )

def F1Rumors_implementation(c):
    a, b = itertools.tee(sorted(c))
    next(b, None)
    r = None
    for k, g in zip(a, b):
        if k != g: continue
        if k != r:
            yield k
            r = k

def F1Rumors(c):
    return list(F1Rumors_implementation(c))

def Edward(a):
    d = {}
    for elem in a:
        if elem in d:
            d[elem] += 1
        else:
            d[elem] = 1
    return [x for x, y in d.items() if y > 1]

def wordsmith(a):
    return pd.Series(a)[pd.Series(a).duplicated()].values

def NikhilPrabhu(li):
    li = li.copy()
    for x in set(li):
        li.remove(x)

    return list(set(li))

def firelynx(a):
    vc = pd.Series(a).value_counts()
    return vc[vc > 1].index.tolist()

def HenryDev(myList):
    newList = set()

    for i in myList:
        if myList.count(i) >= 2:
            newList.add(i)

    return list(newList)

def yota(number_lst):
    seen_set = set()
    duplicate_set = set(x for x in number_lst if x in seen_set or seen_set.add(x))
    return seen_set - duplicate_set

def IgorVishnevskiy(l):
    s=set(l)
    d=[]
    for x in l:
        if x in s:
            s.remove(x)
        else:
            d.append(x)
    return d

def it_duplicates(l):
    return list(duplicates(l))

def it_unique_duplicates(l):
    return list(unique_everseen(duplicates(l)))
Run Code Online (Sandbox Code Playgroud)

基准1

from simple_benchmark import benchmark
import random

funcs = [
    georg_counter, georg_set, georg_set2, georg_set3, RiteshKumar_count, moooeeeep, 
    F1Rumors, Edward, wordsmith, NikhilPrabhu, firelynx,
    HenryDev, yota, IgorVishnevskiy, it_duplicates, it_unique_duplicates
]

args = {2**i: [random.randint(0, 2**(i-1)) for _ in range(2**i)] for i in range(2, 12)}

b = benchmark(funcs, args, 'list size')

b.plot()
Run Code Online (Sandbox Code Playgroud)

基准2

funcs = [
    georg_counter, georg_set, georg_set2, georg_set3, moooeeeep, 
    F1Rumors, Edward, wordsmith, firelynx,
    yota, IgorVishnevskiy, it_duplicates, it_unique_duplicates
]

args = {2**i: [random.randint(0, 2**(i-1)) for _ in range(2**i)] for i in range(2, 20)}

b = benchmark(funcs, args, 'list size')
b.plot()
Run Code Online (Sandbox Code Playgroud)

放弃

1这是我写的第三方图书馆:iteration_utilities.

  • 我要在这里坚持并建议编写一个定制的库来用 C 而不是 Python 来完成工作可能不是正在寻找的答案的精神 - 但这是一种合法的方法!我喜欢答案的宽度和结果的图形显示——很高兴看到它们正在收敛,让我想知道它们是否会随着输入的进一步增加而交叉!问题:与完全随机列表相比,大多数排序列表的结果是什么? (2认同)

小智 10

collections.Counter是python 2.7中的新功能:


Python 2.5.4 (r254:67916, May 31 2010, 15:03:39) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
a = [1,2,3,2,1,5,6,5,5,5]
import collections
print [x for x, y in collections.Counter(a).items() if y > 1]
Type "help", "copyright", "credits" or "license" for more information.
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'Counter'
>>> 
Run Code Online (Sandbox Code Playgroud)

在早期版本中,您可以使用传统的dict代替:

a = [1,2,3,2,1,5,6,5,5,5]
d = {}
for elem in a:
    if elem in d:
        d[elem] += 1
    else:
        d[elem] = 1

print [x for x, y in d.items() if y > 1]
Run Code Online (Sandbox Code Playgroud)


wor*_*ith 10

使用熊猫:

>>> import pandas as pd
>>> a = [1, 2, 1, 3, 3, 3, 0]
>>> pd.Series(a)[pd.Series(a).duplicated()].values
array([1, 3, 3])
Run Code Online (Sandbox Code Playgroud)


yǝs*_*ǝla 9

Python 3.8 one-liner 如果您不想编写自己的算法或使用库:

l = [1,2,3,2,1,5,6,5,5,5]

res = [(x, count) for x, g in groupby(sorted(l)) if (count := len(list(g))) > 1]

print(res)
Run Code Online (Sandbox Code Playgroud)

打印项目和计数:

[(1, 2), (2, 2), (5, 4)]
Run Code Online (Sandbox Code Playgroud)

groupby采用分组功能,因此您可以以不同方式定义分组并Tuple根据需要返回其他字段。

  • 这很棒,但应该提到你需要“from itertools import groupby” (5认同)

Ana*_*thu 8

我想在列表中查找重复项的最有效方法是:

from collections import Counter

def duplicates(values):
    dups = Counter(values) - Counter(set(values))
    return list(dups.keys())

print(duplicates([1,2,3,6,5,2]))
Run Code Online (Sandbox Code Playgroud)

Counter在所有元素上使用一次,然后在所有唯一元素上使用。用第二个减去第一个将只留下重复项。


Nik*_*bhu 7

这是一个简洁明了的解决方案 -

for x in set(li):
    li.remove(x)

li = list(set(li))
Run Code Online (Sandbox Code Playgroud)

  • 在大型列表上这是一个非常讨厌的练习 - 从列表中删除元素非常昂贵! (3认同)

alf*_*sin 7

我们可以使用itertools.groupby来查找所有有重复的项目:

from itertools import groupby

myList  = [2, 4, 6, 8, 4, 6, 12]
# when the list is sorted, groupby groups by consecutive elements which are similar
for x, y in groupby(sorted(myList)):
    #  list(y) returns all the occurences of item x
    if len(list(y)) > 1:
        print x  
Run Code Online (Sandbox Code Playgroud)

输出将是:

4
6
Run Code Online (Sandbox Code Playgroud)

  • 或者更简洁地说:`dupes = [x for x, y in groupby(sorted(myList)) if len(list(y)) > 1]` (2认同)

sup*_*ain 7

尽管其复杂度为 O(n log n),但这似乎有些竞争力,请参阅下面的基准测试。

a = sorted(a)
dupes = list(set(a[::2]) & set(a[1::2]))
Run Code Online (Sandbox Code Playgroud)

排序使重复项彼此相邻,因此它们既位于偶数索引又位于奇数索引。唯一值仅位于偶数奇数索引处,而不是同时位于两者处。因此偶数索引值和奇数索引值的交集就是重复项。

基准测试结果: 基准结果

这使用MSeifert 的基准,但仅使用已接受答案(georgs)中的解决方案、最慢的解决方案、最快的解决方案(排除,it_duplicates因为它不能唯一化重复项)和我的。否则会太拥挤而且颜色太相似。

第一行可能是a.sort()如果我们被允许修改给定的列表,那会更快一些。但基准测试多次重复使用相同的列表,因此修改它会扰乱基准测试。

显然set(a[::2]).intersection(a[1::2])不会创建第二组并且速度更快一点,但是嗯,它也更长一点。


fir*_*ynx 6

我会用熊猫做这件事,因为我经常使用熊猫

import pandas as pd
a = [1,2,3,3,3,4,5,6,6,7]
vc = pd.Series(a).value_counts()
vc[vc > 1].index.tolist()
Run Code Online (Sandbox Code Playgroud)

[3,6]
Run Code Online (Sandbox Code Playgroud)

可能效率不高,但肯定的代码少于其他很多答案,所以我想我会做出贡献

  • 另请注意,pandas包含一个内置的重复函数`pda = pd.Series(a)``print list(pda [pda.duplicated()])` (3认同)

yot*_*ota 6

接受的答案的第三个例子给出了错误的答案,并没有试图给出重复的答案.这是正确的版本:

number_lst = [1, 1, 2, 3, 5, ...]

seen_set = set()
duplicate_set = set(x for x in number_lst if x in seen_set or seen_set.add(x))
unique_set = seen_set - duplicate_set
Run Code Online (Sandbox Code Playgroud)


Hen*_*Dev 6

如何通过检查出现次数简单地遍历列表中的每个元素,然后将它们添加到一个集合,然后打印重复项.希望这有助于那里的人.

myList  = [2 ,4 , 6, 8, 4, 6, 12];
newList = set()

for i in myList:
    if myList.count(i) >= 2:
        newList.add(i)

print(list(newList))
## [4 , 6]
Run Code Online (Sandbox Code Playgroud)


Che*_*van 6

没有转换为列表,可能最简单的方式将是如下所示. 当他们要求不使用套装时,这可能在面试中很有用

a=[1,2,3,3,3]
dup=[]
for each in a:
  if each not in dup:
    dup.append(each)
print(dup)
Run Code Online (Sandbox Code Playgroud)

======= else获取2个独立值和重复值的单独列表

a=[1,2,3,3,3]
uniques=[]
dups=[]

for each in a:
  if each not in uniques:
    uniques.append(each)
  else:
    dups.append(each)
print("Unique values are below:")
print(uniques)
print("Duplicate values are below:")
print(dups)
Run Code Online (Sandbox Code Playgroud)

  • 这不会导致 a (或原始列表)的重复列表,但这会导致 a (或原始列表)的所有唯一元素的列表。完成列表“dup”后,有人会做什么? (2认同)

小智 5

有点晚了,但可能对某些人有帮助。对于更大的列表,我发现这对我有用。

l=[1,2,3,5,4,1,3,1]
s=set(l)
d=[]
for x in l:
    if x in s:
        s.remove(x)
    else:
        d.append(x)
d
[1,3,1]
Run Code Online (Sandbox Code Playgroud)

仅显示所有重复项并保留顺序。