set of list of lists in python

后端 未结 3 1912
-上瘾入骨i
-上瘾入骨i 2020-12-09 02:56

I am having a list of lists :

mat = [[1,2,3],[4,5,6],[1,2,3],[7,8,9],[4,5,6]]

and I want to convert into a set

相关标签:
3条回答
  • 2020-12-09 03:09

    Lists are mutable, therefore unhashable. Use tuples instead

    In [114]: mat = [[1,2,3],[4,5,6],[1,2,3],[7,8,9],[4,5,6]]
    
    In [115]: mat = [tuple(t) for t in mat]
    
    In [116]: matset = set(mat)
    
    In [117]: matset
    Out[117]: {(1, 2, 3), (4, 5, 6), (7, 8, 9)}
    
    In [118]: [list(t) for t in matset]
    Out[118]: [[4, 5, 6], [7, 8, 9], [1, 2, 3]]
    
    0 讨论(0)
  • 2020-12-09 03:17

    @thefourtheye's answer clearly depicts the problem you were facing with non-hashable data types and the way to by pass it so that you can create a set and remove duplicates. This should suffice for most of thef problems but, re-reading your question

    In above case the required answer will be [[1,2,3],[4,5,6],[7,8,9]].

    If the order is important, you need to use OrderedDict

    >>> from collections import OrderedDict
    >>> map(list, OrderedDict.fromkeys(map(tuple, mat)).keys())
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    
    0 讨论(0)
  • 2020-12-09 03:23

    Since the lists are mutable, they cannot be hashed. The best bet is to convert them to a tuple and form a set, like this

    >>> mat = [[1,2,3],[4,5,6],[1,2,3],[7,8,9],[4,5,6]]
    >>> set(tuple(row) for row in mat)
    set([(4, 5, 6), (7, 8, 9), (1, 2, 3)])
    

    We iterate through the mat, one list at a time, convert that to a tuple (which is immutable, so sets are cool with them) and the generator is sent to the set function.

    If you want the result as list of lists, you can extend the same, by converting the result of set function call, to lists, like this

    >>> [list(item) for item in set(tuple(row) for row in mat)]
    [[4, 5, 6], [7, 8, 9], [1, 2, 3]]
    
    0 讨论(0)
提交回复
热议问题