The problem is to go to the news ID in a list and go back to the weight to ensure that the order is not changed.
Intuitive approach
The simplest idea is to:
Copy CodeThe code is as follows:
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 cool enough.
With Set
Another solution is to use set:
Copy CodeThe code is as follows:
ids = [1,4,3,3,4,2,3,4,5,6,1]
ids = List (set (IDS))
This result is not maintained in the original order.
Sort by index again
Finally, this approach solves:
Copy CodeThe code is as follows:
ids = [1,4,3,3,4,2,3,4,5,6,1]
News_ids = List (set (IDS))
News_ids.sort (Ids.index)
Using Itertools.grouby
The article mentions Itertools.grouby from the beginning, which can be used if the list order is not considered:
Copy CodeThe code is as follows:
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
The principle of itertools.groupby can be seen here: http://docs.python.org/2/library/itertools.html#itertools.groupby
Users add: With reduce
The Netizen reatlk the message to the other solution. I add and explain here:
Copy CodeThe code is as follows:
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 run 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 turn IDs into [[], 1,4,3,......] and then take advantage of the features of reduce. Reduce explanation see here: http://docs.python.org/2/library/functions.html#reduce
List of Python go heavy