【问题标题】:Set comprehension gives "unhashable type" (set of list) in Python集合理解在 Python 中给出“不可散列的类型”(列表集)
【发布时间】:2017-02-21 09:46:40
【问题描述】:

我有以下元组列表:

list_of_tuples = [('True', 100, 'Text1'),
                  ('False', 101, 'Text2'),
                  ('True', 102, 'Text3')]

我想将每个元组的所有第二个元素收集到一个集合中:

my_set = set()
my_set.add({tup[1] for tup in list_of_tuples})

但它会引发以下错误:

TypeError: unhashable type: 'set'

当我打印出迭代中的各个元素时,它表明集合推导的结果不包含预期的标量而是列表:

print {tup[1] for tup in list_of_tuples}

set([100, 101, 102])

为什么会这样?为什么这首先将元素放入列表中,然后将列表放入集合中而没有任何提示?我该如何纠正我的解决方案?

【问题讨论】:

  • 你在这里添加 setssets...

标签: python set set-comprehension


【解决方案1】:

您放入集合中的单个项目不能是可变的,因为如果它们发生变化,有效的哈希值就会发生变化,并且检查是否包含的能力就会失效。

set 的内容可以在其生命周期内更改。所以这是非法的。

所以尝试使用这个:

list_of_tuples = [('True', 100, 'Text1'),
                  ('False', 101, 'Text2'),
                  ('True', 102, 'Text3')]


my_set= { tup[1] for tup in list_of_tuples }
# set comprehensions with braces
print my_set

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    您正在定义一个空集,然后尝试在其中添加另一个集。相反,只需直接创建集合:

    my_set = {tup[1] for tup in list_of_tuples}
    

    而您的打印结果正是 Python 表示集合的方式;它不是向您显示有一个列表,而是向您显示一个由 100、101 和 102 组成的集合。

    【讨论】:

      猜你喜欢
      • 2011-12-08
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 2018-06-07
      • 2022-01-11
      • 2019-03-10
      • 2018-12-26
      • 1970-01-01
      相关资源
      最近更新 更多