Finding a union of lists of lists in Python

后端 未结 2 1588
悲哀的现实
悲哀的现实 2021-01-27 18:41

Suppose we have

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

How do I get the union of the three temporary variables?

Expec

2条回答
  •  醉梦人生
    2021-01-27 19:21

    You can use the built-in set to get unique values, but in order to reach this with list objects you need first to transform them in hashable (immutable) objects. An option is 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]]
    

提交回复
热议问题