Python将所有子列表合并到父列表中并删除重复项

时间:2017-11-15 09:25:39

标签: python python-3.x python-2.7

我有很多名单。 我想将所有子列表合并到父列表中 合并后从父列表中删除重复项。

这样做的优化方法是什么?

例如:

x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]

我们如何才能获得x的值:

[' a',' b',' c',1,2,3,4,' z',&# 39; y',' x']

3 个答案:

答案 0 :(得分:4)

使用set

x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]
>>> list(set([item for sublist in x for item in sublist]))
[1, 2, 3, 4, 'z', 'ax', 'a', 'b', 'c', 'x', 'y']

答案 1 :(得分:2)

使用set和chain:

x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]

from itertools import chain

result = list(set(chain.from_iterable(x)))
print(result)

答案 2 :(得分:2)

首先,您可以将list list转换为list,然后将set应用于list

x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]
new_ls=[]
for ls in x:
    new_ls.extend(ls)
print(list(set(new_ls))

输出:

[1, 2, 3, 4, 'ax', 'b', 'y', 'x', 'c', 'z', 'a']