0

我有一个这样的列表:

a =  [['Rostock', 'Lubeck'], ['Rostock', 'Hamburg'], ['Rostock', 'Bremen'], ['Rostock', 'Hannover']]

我只想创建具有唯一元素的列表:

result = ['Rostock', 'Lubeck', 'Hamburg', 'Bremen', 'Hannover']

我怎样才能做到这一点?谢谢

4

3 回答 3

3

假设订单很重要

>>> a =  [['Rostock', 'Lubeck'], ['Rostock', 'Hamburg'], ['Rostock', 'Bremen'], ['Rostock', 'Hannover']]
>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(y for x in a for y in x))
['Rostock', 'Lubeck', 'Hamburg', 'Bremen', 'Hannover']

或等效地:

>>> from itertools import chain
>>> list(OrderedDict.fromkeys(chain.from_iterable(a)))
于 2013-04-30T11:17:14.137 回答
1

如果顺序无关紧要 - 使用 set:

a =  [['Rostock', 'Lubeck'], ['Rostock', 'Hamburg'], ['Rostock', 'Bremen'], ['Rostock', 'Hannover']]
print list(set(y for x in a for y in x))  # prints ['Rostock', 'Hannover', 'Bremen', 'Lubeck', 'Hamburg']
于 2013-04-30T11:18:37.590 回答
0

我发现这更具可读性:

a =  [['Rostock', 'Lubeck'], ['Rostock', 'Hamburg'], ['Rostock', 'Bremen'], ['Rostock', 'Hannover']]

result = []

for x in a:
    for y in x:
        if y not in result:
            result.append(y)

这是输出:

>>> print(result)
['Rostock', 'Lubeck', 'Hamburg', 'Bremen', 'Hannover']
于 2013-04-30T11:23:42.263 回答