Pretty much I need to write a program to check if a list has any duplicates and if it does it removes them and returns a new list with the items that weren’t duplicated/removed. This is what I have but to be honest I do not know what to do.
def remove_duplicates():
t = ['a', 'b', 'c', 'd']
t2 = ['a', 'c', 'd']
for t in t2:
t.append(t.remove())
return t
The common approach to get a unique collection of items is to use a set. Sets are unordered collections of distinct objects. To create a set from any iterable, you can simply pass it to the built-in set() function. If you later need a real list again, you can similarly pass the set to the list() function.
The following example should cover whatever you are trying to do:
As you can see from the example result, the original order is not maintained. As mentioned above, sets themselves are unordered collections, so the order is lost. When converting a set back to a list, an arbitrary order is created.
Maintaining order
If order is important to you, then you will have to use a different mechanism. A very common solution for this is to rely on OrderedDict to keep the order of keys during insertion:
Starting with Python 3.7, the built-in dictionary is guaranteed to maintain the insertion order as well, so you can also use that directly if you are on Python 3.7 or later (or CPython 3.6):
>>> list(dict.fromkeys(t))
[1, 2, 3, 5, 6, 7, 8]
Note that this may have some overhead of creating a dictionary first, and then creating a list from it. If you don’t actually need to preserve the order, you’re often better off using a set, especially because it gives you a lot more operations to work with. Check out this question for more details and alternative ways to preserve the order when removing duplicates.
Finally note that both the set as well as the OrderedDict/dict solutions require your items to be hashable. This usually means that they have to be immutable. If you have to deal with items that are not hashable (e.g. list objects), then you will have to use a slow approach in which you will basically have to compare every item with every other item in a nested loop.
In Python 3.5, the OrderedDict has a C implementation. My timings show that this is now both the fastest and shortest of the various approaches for Python 3.5.
In Python 3.6, the regular dict became both ordered and compact. (This feature is holds for CPython and PyPy but may not present in other implementations). That gives us a new fastest way of deduping while retaining order:
It’s a one-liner: list(set(source_list)) will do the trick.
A set is something that can’t possibly have duplicates.
Update: an order-preserving approach is two lines:
from collections import OrderedDict
OrderedDict((x, True) for x in source_list).keys()
Here we use the fact that OrderedDict remembers the insertion order of keys, and does not change it when a value at a particular key is updated. We insert True as values, but we could insert anything, values are just not used. (set works a lot like a dict with ignored values, too.)
回答 3
>>> t =[1,2,3,1,2,5,6,7,8]>>> t
[1,2,3,1,2,5,6,7,8]>>> s =[]>>>for i in t:if i notin s:
s.append(i)>>> s
[1,2,3,5,6,7,8]
>>> t = [1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> t
[1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> s = []
>>> for i in t:
if i not in s:
s.append(i)
>>> s
[1, 2, 3, 5, 6, 7, 8]
def ordered_set(in_list):
out_list =[]
added = set()for val in in_list:ifnot val in added:
out_list.append(val)
added.add(val)return out_list
为了比较效率,我使用了100个整数的随机样本-62个是唯一的
from random import randint
x =[randint(0,100)for _ in xrange(100)]In[131]: len(set(x))Out[131]:62
这是测量结果
In[129]:%timeit list(OrderedDict.fromkeys(x))10000 loops, best of 3:86.4 us per loop
In[130]:%timeit ordered_set(x)100000 loops, best of 3:15.1 us per loop
好吧,如果将集合从解决方案中删除,会发生什么?
def ordered_set(inlist):
out_list =[]for val in inlist:ifnot val in out_list:
out_list.append(val)return out_list
结果不如OrderedDict差,但仍然是原始解决方案的3倍以上
In[136]:%timeit ordered_set(x)10000 loops, best of 3:52.6 us per loop
A colleague have sent the accepted answer as part of his code to me for a codereview today.
While I certainly admire the elegance of the answer in question, I am not happy with the performance.
I have tried this solution (I use set to reduce lookup time)
def ordered_set(in_list):
out_list = []
added = set()
for val in in_list:
if not val in added:
out_list.append(val)
added.add(val)
return out_list
To compare efficiency, I used a random sample of 100 integers – 62 were unique
from random import randint
x = [randint(0,100) for _ in xrange(100)]
In [131]: len(set(x))
Out[131]: 62
Here are the results of the measurements
In [129]: %timeit list(OrderedDict.fromkeys(x))
10000 loops, best of 3: 86.4 us per loop
In [130]: %timeit ordered_set(x)
100000 loops, best of 3: 15.1 us per loop
Well, what happens if set is removed from the solution?
def ordered_set(inlist):
out_list = []
for val in inlist:
if not val in out_list:
out_list.append(val)
return out_list
The result is not as bad as with the OrderedDict, but still more than 3 times of the original solution
In [136]: %timeit ordered_set(x)
10000 loops, best of 3: 52.6 us per loop
The solution is not so elegant compared to the others, however, compared to pandas.unique(), numpy.unique() allows you also to check if nested arrays are unique along one selected axis.
from collections importOrderedDict,CounterclassContainer:def __init__(self, obj):
self.obj = obj
def __eq__(self, obj):return self.obj == obj
def __hash__(self):try:return hash(self.obj)except:return id(self.obj)classOrderedCounter(Counter,OrderedDict):'Counter that remembers the order elements are first encountered'def __repr__(self):return'%s(%r)'%(self.__class__.__name__,OrderedDict(self))def __reduce__(self):return self.__class__,(OrderedDict(self),)def remd(sequence):
cnt =Counter()for x in sequence:
cnt[Container(x)]+=1return[item.obj for item in cnt]def oremd(sequence):
cnt =OrderedCounter()for x in sequence:
cnt[Container(x)]+=1return[item.obj for item in cnt]
In this answer, will be two sections: Two unique solutions, and a graph of speed for specific solutions.
Removing Duplicate Items
Most of these answers only remove duplicate items which are hashable, but this question doesn’t imply it doesn’t just need hashable items, meaning I’ll offer some solutions which don’t require hashable items.
collections.Counter is a powerful tool in the standard library which could be perfect for this. There’s only one other solution which even has Counter in it. However, that solution is also limited to hashable keys.
To allow unhashable keys in Counter, I made a Container class, which will try to get the object’s default hash function, but if it fails, it will try its identity function. It also defines an eq and a hash method. This should be enough to allow unhashable items in our solution. Unhashable objects will be treated as if they are hashable. However, this hash function uses identity for unhashable objects, meaning two equal objects that are both unhashable won’t work. I suggest you overriding this, and changing it to use the hash of an equivalent mutable type (like using hash(tuple(my_list)) if my_list is a list).
I also made two solutions. Another solution which keeps the order of the items, using a subclass of both OrderedDict and Counter which is named ‘OrderedCounter’. Now, here are the functions:
from collections import OrderedDict, Counter
class Container:
def __init__(self, obj):
self.obj = obj
def __eq__(self, obj):
return self.obj == obj
def __hash__(self):
try:
return hash(self.obj)
except:
return id(self.obj)
class OrderedCounter(Counter, OrderedDict):
'Counter that remembers the order elements are first encountered'
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
def __reduce__(self):
return self.__class__, (OrderedDict(self),)
def remd(sequence):
cnt = Counter()
for x in sequence:
cnt[Container(x)] += 1
return [item.obj for item in cnt]
def oremd(sequence):
cnt = OrderedCounter()
for x in sequence:
cnt[Container(x)] += 1
return [item.obj for item in cnt]
remd is non-ordered sorting, oremd is ordered sorting. You can clearly tell which one is faster, but I’ll explain anyways. The non-ordered sorting is slightly faster. It keeps less data, since it doesn’t need order.
Now, I also wanted to show the speed comparisons of each answer. So, I’ll do that now.
Which Function is the Fastest?
For removing duplicates, I gathered 10 functions from a few answers. I calculated the speed of each function and put it into a graph using matplotlib.pyplot.
I divided this into three rounds of graphing. A hashable is any object which can be hashed, an unhashable is any object which cannot be hashed. An ordered sequence is a sequence which preserves order, an unordered sequence does not preserve order. Now, here are a few more terms:
Unordered Hashable was for any method which removed duplicates, which didn’t necessarily have to keep the order. It didn’t have to work for unhashables, but it could.
Ordered Hashable was for any method which kept the order of the items in the list, but it didn’t have to work for unhashables, but it could.
Ordered Unhashable was any method which kept the order of the items in the list, and worked for unhashables.
On the y-axis is the amount of seconds it took.
On the x-axis is the number the function was applied to.
We generated sequences for unordered hashables and ordered hashables with the following comprehension: [list(range(x)) + list(range(x)) for x in range(0, 1000, 10)]
For ordered unhashables: [[list(range(y)) + list(range(y)) for y in range(x)] for x in range(0, 1000, 10)]
Note there is a ‘step’ in the range because without it, this would’ve taken 10x as long. Also because in my personal opinion, I thought it might’ve looked a little easier to read.
Also note the keys on the legend are what I tried to guess as the most vital parts of the function. As for what function does the worst or best? The graph speaks for itself.
With that settled, here are the graphs.
Unordered Hashables
(Zoomed in)
Ordered Hashables
(Zoomed in)
Ordered Unhashables
(Zoomed in)
回答 11
我的清单上有一个字典,所以我不能使用上述方法。我得到了错误:
TypeError: unhashable type:
因此,如果您关心订单和/或某些项目无法散列。然后,您可能会发现这很有用:
def make_unique(original_list):
unique_list =[][unique_list.append(obj)for obj in original_list if obj notin unique_list]return unique_list
# from functools import reduce <-- add this import on Python 3def 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 orderdef 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]]))]
All the order-preserving approaches I’ve seen here so far either use naive comparison (with O(n^2) time-complexity at best) or heavy-weight OrderedDicts/set+list combinations that are limited to hashable inputs. Here is a hash-independent O(nlogn) solution:
Update added the key argument, documentation and Python 3 compatibility.
# 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]]))]
回答 13
如果您想保留订单,并且不使用任何外部模块,则可以通过以下简便方法进行操作:
>>> 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]
Note: This method preserves the order of appearance, so, as seen above, nine will come after one because it was the first time it appeared. This however, is the same result as you would get with doing
from collections import OrderedDict
ulist=list(OrderedDict.fromkeys(l))
but it is much shorter, and runs faster.
This works because each time the fromkeys function tries to create a new key, if the value already exists it will simply overwrite it. This wont affect the dictionary at all however, as fromkeys creates a dictionary where all keys have the value None, so effectively it eliminates all duplicates this way.
回答 14
您也可以这样做:
>>> t =[1,2,3,3,2,4,5,6]>>> s =[x for i, x in enumerate(t)if i == t.index(x)]>>> s
[1,2,3,4,5,6]
import sets
t = sets.Set(['a', 'b', 'c', 'd'])
t1 = sets.Set(['a', 'b', 'c'])
print t | t1
print t - t1
回答 16
通过保留订单来减少变体:
假设我们有清单:
l =[5,6,6,1,1,2,2,3,4]
减少变体(无效):
>>> reduce(lambda r, v: v in r and r or r +[v], l,[])[5,6,1,2,3,4]
速度提高5倍,但功能更先进
>>> reduce(lambda r, v: v in r[1]and r or(r[0].append(v)or r[1].add(v))or r, l,([], set()))[0][5,6,1,2,3,4]
说明:
default =(list(), set())# user list to keep order# use set to make lookup fasterdef reducer(result, item):if item notin result[1]:
result[0].append(item)
result[1].add(item)return result
reduce(reducer, l, default)[0]
>>> reduce(lambda r, v: v in r and r or r + [v], l, [])
[5, 6, 1, 2, 3, 4]
5 x faster but more sophisticated
>>> reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, l, ([], set()))[0]
[5, 6, 1, 2, 3, 4]
Explanation:
default = (list(), set())
# user list to keep order
# use set to make lookup faster
def reducer(result, item):
if item not in result[1]:
result[0].append(item)
result[1].add(item)
return result
reduce(reducer, l, default)[0]
There are many other answers suggesting different ways to do this, but they’re all batch operations, and some of them throw away the original order. That might be okay depending on what you need, but if you want to iterate over the values in the order of the first instance of each value, and you want to remove the duplicates on-the-fly versus all at once, you could use this generator:
def uniqify(iterable):
seen = set()
for item in iterable:
if item not in seen:
seen.add(item)
yield item
This returns a generator/iterator, so you can use it anywhere that you can use an iterator.
for unique_item in uniqify([1, 2, 3, 4, 3, 2, 4, 5, 6, 7, 6, 8, 8]):
print(unique_item, end=' ')
print()
def remove_duplicates(list):''' Removes duplicate items from a list '''
singles_list =[]for element in list:if element notin singles_list:
singles_list.append(element)return singles_list
This one cares about the order without too much hassle (OrderdDict & others). Probably not the most Pythonic way, nor shortest way, but does the trick:
def remove_duplicates(list):
''' Removes duplicate items from a list '''
singles_list = []
for element in list:
if element not in singles_list:
singles_list.append(element)
return singles_list
回答 24
下面的代码很容易删除列表中的重复项
def remove_duplicates(x):
a =[]for i in x:if i notin a:
a.append(i)return a
print remove_duplicates([1,2,2,3,3,4])
def deduplicate(sequence):
visited = set()
adder = visited.add # get rid of qualification overhead
out =[adder(item)or item for item in sequence if item notin visited]return out
Here’s the fastest pythonic solution comaring to others listed in replies.
Using implementation details of short-circuit evaluation allows to use list comprehension, which is fast enough. visited.add(item) always returns None as a result, which is evaluated as False, so the right-side of or would always be the result of such an expression.
Time it yourself
def deduplicate(sequence):
visited = set()
adder = visited.add # get rid of qualification overhead
out = [adder(item) or item for item in sequence if item not in visited]
return out
回答 26
使用set:
a =[0,1,2,3,4,3,3,4]
a = list(set(a))print a
使用独特的:
import numpy as np
a =[0,1,2,3,4,3,3,4]
a = np.unique(a).tolist()print a
>>> n = [1, 2, 3, 4, 1, 1]
>>> n
[1, 2, 3, 4, 1, 1]
>>> m = sorted(list(set(n)))
>>> m
[1, 2, 3, 4]
回答 29
Python内置类型的魔力
在python中,仅通过python的内置类型,即可轻松处理此类复杂情况。
让我告诉你怎么做!
方法1:一般情况
删除列表中重复元素并仍然保持排序顺序的方式(1行代码)
line =[1,2,3,1,2,5,6,7,8]
new_line = sorted(set(line), key=line.index)# remove duplicated elementprint(new_line)
您将得到结果
[1,2,3,5,6,7,8]
方法2:特例
TypeError: unhashable type:'list'
处理不可散列的特殊情况(3行代码)
line=[['16.4966155686595','-27.59776154691','52.3786295521147'],['16.4966155686595','-27.59776154691','52.3786295521147'],['17.6508629295574','-27.143305738671','47.534955022564'],['17.6508629295574','-27.143305738671','47.534955022564'],['18.8051102904552','-26.688849930432','42.6912804930134'],['18.8051102904552','-26.688849930432','42.6912804930134'],['19.5504702331098','-26.205884452727','37.7709192714727'],['19.5504702331098','-26.205884452727','37.7709192714727'],['20.2929416861422','-25.722717575124','32.8500163147157'],['20.2929416861422','-25.722717575124','32.8500163147157']]
tuple_line =[tuple(pt)for pt in line]# convert list of list into list of tuple
tuple_new_line = sorted(set(tuple_line),key=tuple_line.index)# remove duplicated element
new_line =[list(t)for t in tuple_new_line]# convert list of tuple into list of listprint(new_line)
In python, it is very easy to process the complicated cases like this and only by python’s built-in type.
Let me show you how to do !
Method 1: General Case
The way (1 line code) to remove duplicated element in list and still keep sorting order
line = [1, 2, 3, 1, 2, 5, 6, 7, 8]
new_line = sorted(set(line), key=line.index) # remove duplicated element
print(new_line)
You will get the result
[1, 2, 3, 5, 6, 7, 8]
Method 2: Special Case
TypeError: unhashable type: 'list'
The special case to process unhashable (3 line codes)
line=[['16.4966155686595', '-27.59776154691', '52.3786295521147']
,['16.4966155686595', '-27.59776154691', '52.3786295521147']
,['17.6508629295574', '-27.143305738671', '47.534955022564']
,['17.6508629295574', '-27.143305738671', '47.534955022564']
,['18.8051102904552', '-26.688849930432', '42.6912804930134']
,['18.8051102904552', '-26.688849930432', '42.6912804930134']
,['19.5504702331098', '-26.205884452727', '37.7709192714727']
,['19.5504702331098', '-26.205884452727', '37.7709192714727']
,['20.2929416861422', '-25.722717575124', '32.8500163147157']
,['20.2929416861422', '-25.722717575124', '32.8500163147157']]
tuple_line = [tuple(pt) for pt in line] # convert list of list into list of tuple
tuple_new_line = sorted(set(tuple_line),key=tuple_line.index) # remove duplicated element
new_line = [list(t) for t in tuple_new_line] # convert list of tuple into list of list
print (new_line)