5

你知道,要翻列表:

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的方法是什么?

4

3 回答 3

14
>>> a = [["hello", "hi"], ["hello", "hi"], ["how", "what"], ["hello", "hi"], ["how", "what"]]
>>> set(map(tuple, a))
set([('how', 'what'), ('hello', 'hi')])
于 2012-06-29T12:09:18.670 回答
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']]
于 2012-06-29T12:19:31.193 回答
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')]
于 2012-06-29T12:28:49.847 回答