python列表去重

Python列表去掉重复元素的一种方法:

>>> L = [1, 2, 3, 4, 1, 2, 3, 4, 5]

>>> [x for x in L if x not in locals()[‘_[1]’]]

[1, 2, 3, 4, 5]
解释如下:
18

down vote Referencing a list comprehension as it is being built…

You can reference a list comprehension as it is being built by the symbol ‘_[1]’. For example, the following function unique-ifies a list of elements without changing their order by referencing its list comprehension.

def unique(my_list):

return [x for x in mylist if x not in locals()[‘[1]’]]
 

再加一种方法:利用集合去重

>>> a=[1,2,2,3,4,7,9,2,4,1]

>>> list(set(a))

[1, 2, 3, 4, 7, 9]