我有一个这样的列表:
a = [['Rostock', 'Lubeck'], ['Rostock', 'Hamburg'], ['Rostock', 'Bremen'], ['Rostock', 'Hannover']]
我只想创建具有唯一元素的列表:
result = ['Rostock', 'Lubeck', 'Hamburg', 'Bremen', 'Hannover']
我怎样才能做到这一点?谢谢
假设订单很重要
>>> 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)))
如果顺序无关紧要 - 使用 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']
我发现这更具可读性:
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']