我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?
当前回答
不幸的是。这里的大多数答案要么不保持顺序,要么太长。这里有一个简单的、有序的答案。
s = [1,2,3,4,5,2,5,6,7,1,3,9,3,5]
x=[]
[x.append(i) for i in s if i not in x]
print(x)
这将得到x,删除重复项,但保留顺序。
其他回答
到目前为止,我看到的所有保持顺序的方法要么使用朴素比较(时间复杂度最多为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]]))]
您可以使用以下函数:
def rem_dupes(dup_list):
yooneeks = []
for elem in dup_list:
if elem not in yooneeks:
yooneeks.append(elem)
return yooneeks
例子:
my_list = ['this','is','a','list','with','dupicates','in', 'the', 'list']
用法:
rem_dupes(my_list)
[‘这个’,‘是’,‘“,“列表”,“与”,“dupicates”,“在”,“的”)
尝试使用集合:
import sets
t = sets.Set(['a', 'b', 'c', 'd'])
t1 = sets.Set(['a', 'b', 'c'])
print t | t1
print t - t1
检查字符串'a'和'b'
clean_list = []
for ele in raw_list:
if 'b' in ele or 'a' in ele:
pass
else:
clean_list.append(ele)
这是一行代码:list(set(source_list))就可以了。
集合是不可能有重复的东西。
更新:一个保持顺序的方法有两行:
from collections import OrderedDict
OrderedDict((x, True) for x in source_list).keys()
这里我们使用OrderedDict记住键的插入顺序,并且在更新特定键上的值时不更改它。我们插入True作为值,但我们可以插入任何值,只是不使用值。(set的工作原理也很像一个忽略值的字典。)