2014-10-19 55 views
0

假设我们有查找列表的列表的工会在Python

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

我如何获得这三个临时变量的工会吗?

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

+0

'[1,2,3,4,5]'是联盟 – 2014-10-19 00:31:19

回答

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 
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]]