【问题标题】:set of list of lists in pythonpython中的列表列表集
【发布时间】:2014-12-18 07:12:01
【问题描述】:

我有一个列表列表

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

我想转换成一个 set,即删除重复列表并从中创建一个新列表,其中仅包含 unique 列表。

在上述情况下,所需的答案将是

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

但是当我做set(mat) 时,它给了我错误

TypeError: unhashable type: 'list'

你能解决我的问题吗?提前致谢!

【问题讨论】:

  • 订单重要吗?

标签: python list set


【解决方案1】:

@thefourtheye 的回答清楚地描述了您在使用不可散列数据类型时遇到的问题以及绕过它的方法,以便您可以创建一个集合并删除重复项。这应该足以解决大多数问题,但是,请重新阅读您的问题

在上述情况下,所需的答案将是 [[1,2,3],[4,5,6],[7,8,9]]。

如果顺序很重要,需要使用OrderedDict

>>> from collections import OrderedDict
>>> map(list, OrderedDict.fromkeys(map(tuple, mat)).keys())
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

【讨论】:

    【解决方案2】:

    自从lists are mutable, they cannot be hashed。最好的办法是将它们转换为元组并形成一个集合,像这样

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

    我们遍历mat,一次一个列表,将其转换为一个元组(它是不可变的,所以sets 对它们很酷)并将生成器发送到set 函数。

    如果您希望将结果作为列表列表,您可以通过将set 函数调用的结果转换为列表来扩展相同的列表,就像这样

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

    【讨论】:

      【解决方案3】:

      列表是可变的,因此不可散列。改用元组

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

      【讨论】:

        猜你喜欢
        • 2017-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-15
        • 1970-01-01
        • 1970-01-01
        • 2011-08-31
        • 2011-02-19
        相关资源
        最近更新 更多