是否有内置的程序在保留顺序的同时从Python列表中删除重复项? 我知道我可以使用集合来删除重复项,但这会破坏原始顺序。 我也知道我可以这样滚动自己:
def uniq(input):
output = []
for x in input:
if x not in output:
output.append(x)
return output
但是如果可能的话,我想利用一个内置的或更Pythonic的习惯用法。
相关问题: 在Python中,从列表中删除重复项以使所有元素在保持顺序唯一的同时最快的算法是什么?
#1楼
您可以引用列表理解,因为它是由符号“ _ [1]”构建的。
例如,以下函数通过引用元素的列表理解来唯一化元素列表,而不更改其顺序。
def unique(my_list):
return [x for x in my_list if x not in locals()['_[1]']]
演示:
l1 = [1, 2, 3, 4, 1, 2, 3, 4, 5]
l2 = [x for x in l1 if x not in locals()['_[1]']]
print l2
输出:
[1, 2, 3, 4, 5]
#2楼
sequence = ['1', '2', '3', '3', '6', '4', '5', '6']
unique = []
[unique.append(item) for item in sequence if item not in unique]
唯一→ ['1', '2', '3', '6', '4', '5']
#3楼
我想如果您想维持订单,
您可以尝试以下方法:
list1 = ['b','c','d','b','c','a','a']
list2 = list(set(list1))
list2.sort(key=list1.index)
print list2
或者类似地,您可以执行以下操作:
list1 = ['b','c','d','b','c','a','a']
list2 = sorted(set(list1),key=list1.index)
print list2
您也可以这样做:
list1 = ['b','c','d','b','c','a','a']
list2 = []
for i in list1:
if not i in list2:
list2.append(i)`
print list2
也可以这样写:
list1 = ['b','c','d','b','c','a','a']
list2 = []
[list2.append(i) for i in list1 if not i in list2]
print list2
#4楼
编辑2016
正如Raymond所指出的那样 ,在Python 3.5+中,其中OrderedDict
是用C实现的,列表理解方法将比OrderedDict
慢(除非您实际上需要列表的末尾-即使如此,仅当输入非常短时)。 因此,3.5+的最佳解决方案是OrderedDict
。
重要编辑2015
正如@abarnert所指出的那样, more_itertools
库( pip install more_itertools
)包含一个unique_everseen
函数,该函数旨在解决此问题而not seen.add
在列表理解中造成任何不可读的 ( not seen.add
) 突变 。 这也是最快的解决方案:
>>> from more_itertools import unique_everseen
>>> items = [1, 2, 0, 1, 3, 2]
>>> list(unique_everseen(items))
[1, 2, 0, 3]
只需导入一个简单的库,就不会有黑客入侵。 这来自itertools配方unique_everseen
的实现,如下所示:
def unique_everseen(iterable, key=None):
"List unique elements,