Finding combining list of lists in Python

Let's pretend that

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

How to get the union of three temporary variables?

Expected Result: [[1,2,3],[3,4,5]] .

0
python
source share
2 answers

You can use the built-in set to get unique values, but to achieve this with list objects, you need to first convert them to hash objects (immutable). tuple option:

 >>> 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]] 
+2
source share

I created matrix to easily change the code for generic input:

 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 
+1
source share

All Articles