在Python中查找列表列表的联合

时间:2014-10-19 00:15:27

标签: python

假设我们有

 temp1 = [1, 2, 3]
 temp2 = [1, 2, 3]
 temp3 = [3, 4, 5]

如何获得三个临时变量的并集?

预期结果:[[1,2,3],[3,4,5]]

2 个答案:

答案 0 :(得分:2)

您可以使用内置的set来获取唯一值,但为了使用list对象实现此目标,首先需要在可散列(不可变)对象中对它们进行转换。选项为tuple

>>> temp1 = [1,2,3]
>>> temp2 = [1,2,3]
>>> temp3 = [3,4,5]
>>> my_lists = [temp1, temp2, temp3]

>>> unique_values = set(map(tuple, my_lists))
>>> unique_values  # a set of tuples
{(1, 2, 3), (4, 5, 6)}

>>> unique_lists = list(map(list, unique_values))
>>> unique_lists  # a list of lists again
[[4, 5, 6], [1, 2, 3]]

答案 1 :(得分:1)

我创建了一个matrix来轻松更改代码以进行广义输入:

temp1=[1,2,3]
temp2=[3,2,6]
temp3=[1,2,3]
matrix = [temp1, temp2, temp3]

result = []
for l in matrix:
    if l not in result:
        result.append(l)

print result