set of list of lists in python

徘徊边缘 提交于 2020-02-12 11:50:32

问题


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 i.e. remove the repeating lists and creating a new list out of it which will only contain the unique lists.

In above case the required answer will be

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

But when I do set(mat), it gives me error

TypeError: unhashable type: 'list'

Can you please solve my problem. Thanks in advance!


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/26514179/set-of-list-of-lists-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!