Python - 快速删除此列表中的重复项?

时间:2012-06-29 12:08:16

标签: python list

你知道,打开清单:

a = ["hello", "hello", "hi", "hi", "hey"]

进入列表:

b = ["hello", "hi", "hey"]

你只需这样做:

b = list(set(a))

快速和pythonic。

但如果我需要改变这个清单怎么办:

a = [["hello", "hi"], ["hello", "hi"], ["how", "what"], ["hello", "hi"], 
     ["how", "what"]] 

到:

b = [["hello", "hi"], ["how", "what"]]

这样做的pythonic方式是什么?

3 个答案:

答案 0 :(得分:14)

>>> a = [["hello", "hi"], ["hello", "hi"], ["how", "what"], ["hello", "hi"], ["how", "what"]]
>>> set(map(tuple, a))
set([('how', 'what'), ('hello', 'hi')])

答案 1 :(得分:1)

只是另一种不太好的方法(尽管它适用于不可用的对象,只要它们是可订购的)

>>> from itertools import groupby
>>> a = [["hello", "hi"], ["hello", "hi"], ["how", "what"], ["hello", "hi"], ["how", "what"]]
>>> [k for k, g in groupby(sorted(a))]
[['hello', 'hi'], ['how', 'what']]

答案 2 :(得分:0)

如果需要保留原始订单并且您有Python 2.7 +

>>> from collections import OrderedDict
>>> a = [["hello", "hi"], ["hello", "hi"], ["how", "what"], ["hello", "hi"], ["how", "what"]]
>>> list(OrderedDict.fromkeys(map(tuple, a)))
[('hello', 'hi'), ('how', 'what')]