我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?
当前回答
如果你想保持顺序,不使用任何外部模块,这里有一个简单的方法:
>>> t = [1, 9, 2, 3, 4, 5, 3, 6, 7, 5, 8, 9]
>>> list(dict.fromkeys(t))
[1, 9, 2, 3, 4, 5, 6, 7, 8]
注意:这种方法保留了出现的顺序,因此,如上所示,9将在1之后,因为它是第一次出现。然而,这和你做的结果是一样的
from collections import OrderedDict
ulist=list(OrderedDict.fromkeys(l))
但它更短,跑得更快。
这是因为每次fromkeys函数尝试创建一个新键时,如果值已经存在,它就会简单地覆盖它。然而,这不会影响字典,因为fromkeys创建的字典中所有键的值都为None,因此有效地消除了所有重复的值。
其他回答
如果你不关心顺序,想要一些不同于上面建议的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/
不使用set
data=[1, 2, 3, 1, 2, 5, 6, 7, 8]
uni_data=[]
for dat in data:
if dat not in uni_data:
uni_data.append(dat)
print(uni_data)
如果列表是有序的,则可以使用以下方法对其进行迭代,跳过重复的值。这对于处理内存消耗低的大列表特别有用,可以避免构建dict或set的成本:
def uniq(iterator):
prev = None
for item in iterator:
if item != prev:
prev = item
yield item
然后:
for item in uniq([1, 1, 3, 5, 5, 6]):
print(item, end=' ')
输出将是:1 3 5 6
要返回一个列表对象,你可以这样做:
>>> print(list(uniq([1, 1, 3, 5, 5, 6])))
[1, 3, 5, 6]
到目前为止,我看到的所有保持顺序的方法要么使用朴素比较(时间复杂度最多为O(n^2)),要么使用限制于可哈希输入的重载OrderedDicts/set+list组合。下面是一个与哈希无关的O(nlogn)解决方案:
更新增加了关键参数、文档和Python 3兼容性。
# from functools import reduce <-- add this import on Python 3
def uniq(iterable, key=lambda x: x):
"""
Remove duplicates from an iterable. Preserves order.
:type iterable: Iterable[Ord => A]
:param iterable: an iterable of objects of any orderable type
:type key: Callable[A] -> (Ord => B)
:param key: optional argument; by default an item (A) is discarded
if another item (B), such that A == B, has already been encountered and taken.
If you provide a key, this condition changes to key(A) == key(B); the callable
must return orderable objects.
"""
# Enumerate the list to restore order lately; reduce the sorted list; restore order
def append_unique(acc, item):
return acc if key(acc[-1][1]) == key(item[1]) else acc.append(item) or acc
srt_enum = sorted(enumerate(iterable), key=lambda item: key(item[1]))
return [item[1] for item in sorted(reduce(append_unique, srt_enum, [srt_enum[0]]))]
它需要安装一个第三方模块,但包iteration_utilities包含一个unique_everseen1函数,可以删除所有重复的同时保留顺序:
>>> from iteration_utilities import unique_everseen
>>> list(unique_everseen(['a', 'b', 'c', 'd'] + ['a', 'c', 'd']))
['a', 'b', 'c', 'd']
如果你想避免列表添加操作的开销,你可以使用itertools。链:
>>> from itertools import chain
>>> list(unique_everseen(chain(['a', 'b', 'c', 'd'], ['a', 'c', 'd'])))
['a', 'b', 'c', 'd']
unique_everseen也适用于列表中有不可哈希项(例如列表)的情况:
>>> from iteration_utilities import unique_everseen
>>> list(unique_everseen([['a'], ['b'], 'c', 'd'] + ['a', 'c', 'd']))
[['a'], ['b'], 'c', 'd', 'a']
然而,这将比项目是可哈希的(多)慢。
1披露:我是iteration_utilities-library的作者。