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]

解释如下:

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 my_list if x not in locals()['_[1]']]

posted @ 2011-09-17 12:50  SophiaTang  阅读(1027)  评论(0编辑  收藏  举报