我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?


当前回答

也有使用Pandas和Numpy的解决方案。它们都返回numpy数组,所以如果你想要一个列表,你必须使用.tolist()函数。

t=['a','a','b','b','b','c','c','c']
t2= ['c','c','b','b','b','a','a','a']

熊猫的解决方案

唯一使用Pandas函数():

import pandas as pd
pd.unique(t).tolist()
>>>['a','b','c']
pd.unique(t2).tolist()
>>>['c','b','a']

Numpy解决方案

使用numpy函数unique()。

import numpy as np
np.unique(t).tolist()
>>>['a','b','c']
np.unique(t2).tolist()
>>>['a','b','c']

注意,numpy.unique()也对值进行排序。所以列表t2是有序返回的。如果你想保留顺序,可以这样回答:

_, idx = np.unique(t2, return_index=True)
t2[np.sort(idx)].tolist()
>>>['c','b','a']

与其他解决方案相比,该解决方案并不那么优雅,但是,与pandas.unique()相比,numpy.unique()还允许您检查嵌套数组在选定的轴上是否唯一。

其他回答

这里有一个例子,返回没有重复的列表,保持顺序。不需要任何外部导入。

def GetListWithoutRepetitions(loInput):
    # return list, consisting of elements of list/tuple loInput, without repetitions.
    # Example: GetListWithoutRepetitions([None,None,1,1,2,2,3,3,3])
    # Returns: [None, 1, 2, 3]

    if loInput==[]:
        return []

    loOutput = []

    if loInput[0] is None:
        oGroupElement=1
    else: # loInput[0]<>None
        oGroupElement=None

    for oElement in loInput:
        if oElement<>oGroupElement:
            loOutput.append(oElement)
            oGroupElement = oElement
    return loOutput

在Python 2.7中,从可迭代对象中删除重复项同时保持其原始顺序的新方法是:

>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']

在Python 3.5中,OrderedDict有一个C实现。我的计时显示,这是Python 3.5的各种方法中最快和最短的。

在Python 3.6中,常规字典变得既有序又紧凑。(此特性适用于CPython和PyPy,但在其他实现中可能不存在)。这为我们提供了一种新的最快的方法,在保持秩序的同时减少数据:

>>> list(dict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']

在Python 3.7中,常规字典保证在所有实现中都是有序的。所以,最短最快的解决方案是:

>>> list(dict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']

我用纯python函数做到了这一点。当您的项目值是JSON时,这是有效的。

[i for n, i in enumerate(items) if i not in items[n + 1 :]]

这只是一个可读的函数,很容易理解,我已经使用了dict数据结构,我已经使用了一些内置函数和更好的复杂度O(n)

def undup(dup_list):
    b={}
    for i in dup_list:
        b.update({i:1})
    return b.keys()
a=["a",'b','a']
print undup(a)

免责声明:你可能会得到缩进错误(如果复制和粘贴),使用上述代码与适当的缩进粘贴之前

def remove_duplicates(input_list):
  if input_list == []:
    return []
  #sort list from smallest to largest
  input_list=sorted(input_list)
  #initialize ouput list with first element of the       sorted input list
  output_list = [input_list[0]]
  for item in input_list:
    if item >output_list[-1]:
      output_list.append(item)
  return output_list