Multiple methods of de duplication of a list in python
- 2020-04-02 14:09:30
- OfStack
I ran into a problem today, using the function itertools.groupby at a colleague's random prompt. But it didn't work.
The problem is to de-weight the news ids in a list, and then keep them in the same order.
Intuitive way
The simplest way to think about it is:
ids = [1,2,3,3,4,2,3,4,5,6,1]
news_ids = []
for id in ids:
if id not in news_ids:
news_ids.append(id)
print news_ids
It works, but it doesn't look great.
With the set
Another solution is to use set:
ids = [1,4,3,3,4,2,3,4,5,6,1]
ids = list(set(ids))
The result is that the order is not maintained.
Sort again by index
Finally, the solution is:
ids = [1,4,3,3,4,2,3,4,5,6,1]
news_ids = list(set(ids))
news_ids.sort(ids.index)
Use the itertools grouby
Itertools.grouby was mentioned at the beginning of the article, which you can use if you don't consider the list order:
ids = [1,4,3,3,4,2,3,4,5,6,1]
ids.sort()
it = itertools.groupby(ids)
for k, g in it:
print k
About the itertools. Groupby principle can see here: (link: http://docs.python.org/2/library/itertools.html#itertools.groupby)
Use reduce
Netizen reatlk left a message for another solution. I add and explain here:
In [5]: ids = [1,4,3,3,4,2,3,4,5,6,1]
In [6]: func = lambda x,y:x if y in x else x + [y]
In [7]: reduce(func, [[], ] + ids)
Out[7]: [1, 4, 3, 2, 5, 6]
Above is the code I ran in ipython, where lambda x,y:x if y in x else x+[y] is equivalent to lambda x,y: y in x and x or x+[y].
The idea is to change ids to [[], 1,4,3...] , and then take advantage of the features of reduce. Reduce explanation: see here (link: http://docs.python.org/2/library/functions.html#reduce)