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


当前回答

这只是一个可读的函数,很容易理解,我已经使用了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)

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

其他回答

检查字符串'a'和'b'

clean_list = []
    for ele in raw_list:
        if 'b' in ele or 'a' in ele:
            pass
        else:
            clean_list.append(ele)

在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']

您可以通过使用集合简单地做到这一点。

步骤1:获取列表的不同元素 Step2获取列表的公共元素 3 .结合

In [1]: a = ["apples", "bananas", "cucumbers"]

In [2]: b = ["pears", "apples", "watermelons"]

In [3]: set(a).symmetric_difference(b).union(set(a).intersection(b))
Out[3]: {'apples', 'bananas', 'cucumbers', 'pears', 'watermelons'}

如果你不关心顺序,想要一些不同于上面建议的python方式(也就是说,它可以在面试中使用),那么:

def remove_dup(arr):
    size = len(arr)
    j = 0    # To store index of next unique element
    for i in range(0, size-1):
        # If current element is not equal
        # to next element then store that
        # current element
        if(arr[i] != arr[i+1]):
            arr[j] = arr[i]
            j+=1

    arr[j] = arr[size-1] # Store the last element as whether it is unique or repeated, it hasn't stored previously

    return arr[0:j+1]

if __name__ == '__main__':
    arr = [10, 10, 1, 1, 1, 3, 3, 4, 5, 6, 7, 8, 8, 9]
    print(remove_dup(sorted(arr)))

时间复杂度:O(n)

辅助空间:O(n)

参考:http://www.geeksforgeeks.org/remove-duplicates-sorted-array/

另一种解决方案可能如下。以item为键,index为值,从列表中创建一个字典,然后打印字典键。

>>> lst = [1, 3, 4, 2, 1, 21, 1, 32, 21, 1, 6, 5, 7, 8, 2]
>>>
>>> dict_enum = {item:index for index, item in enumerate(lst)}
>>> print dict_enum.keys()
[32, 1, 2, 3, 4, 5, 6, 7, 8, 21]