set of list of lists in python

后端 未结 3 1954
-上瘾入骨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]]
    

提交回复
热议问题