理解 Python 集合的行为 [英] Understanding the behavior of Python's set

查看:38
本文介绍了理解 Python 集合的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内置类型 set 的文档说:

类集([可迭代])

<块引用>

返回一个新的集合或冻结集合对象其元素取自可迭代的.集合的元素必须是可哈希的.

没关系,但为什么这样做:

<预><代码>>>>l = 范围(10)>>>s = 集合(l)>>>秒设置([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

这不会:

 >>>s.add([10])回溯(最近一次调用最后一次):文件<pyshell#7>",第 1 行,在 <module> 中s.add([10])类型错误:不可散列的类型:列表"

两者都是列表.初始化期间是否发生了一些魔法?

解决方案

当你初始化一个集合时,你提供一个值列表,这些值必须每个都是可散列的.

s = set()s.add([10])

相同

s = set([[10]])

抛出与您现在看到的相同的错误.

The documentation for the built-in type set says:

class set([iterable])

Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable.

That is all right but why does this work:

>>> l = range(10)
>>> s = set(l)
>>> s
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

And this doesn't:

 >>> s.add([10])

    Traceback (most recent call last):
      File "<pyshell#7>", line 1, in <module>
        s.add([10])
    TypeError: unhashable type: 'list'

Both are lists. Is some magic happening during the initialization?

解决方案

When you initialize a set, you provide a list of values that must each be hashable.

s = set()
s.add([10])

is the same as

s = set([[10]])

which throws the same error that you're seeing right now.

这篇关于理解 Python 集合的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆