frozenset() - 何时可以使用它们的示例 [英] frozenset() - Example of when one might use them
问题描述
能否给我提供一些简单的例子,说明什么时候使用frozenset是最好的选择,可以帮助我更好地理解这个概念.
frozenset()
对象可以用作字典键和 inside set 的值()
和 frozenset()
对象,其中 set
对象不能.set()
值是可变且不可散列的,frozenset()
值是不可变且可散列的.
它们对set
对象的作用就像tuple
对象对list
对象的作用一样.
演示:
<预><代码>>>>s = set([1, 2])>>>fs = 冻结集>>>adict = {}>>>adict[s] = 42 # set as key 不起作用回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:不可散列的类型:设置">>>adict[fs] = 42 # 一个冻结集作为关键工作>>>s.add(s) # 一个集合作为集合中的值不起作用回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:不可散列的类型:设置">>>s.add(fs) # 冻结集作为集合中的值有效最近的 Python 版本将优化集合文字的使用:
if somevar in {'foo', 'bar', 'baz'}:
通过使用字节码存储一个 frozenset()
常量:
因为集合文字不能被改变反正;这使得使用集合进行测试非常有效.常规 set()
不能以这种方式存储,因为这将允许您改变与字节对象一起存储的常量.
Could I be supplied with some simple examples of when using a frozenset would be the best option to help me understand the concept more please.
frozenset()
objects can be used as dictionary keys and as values inside of set()
and frozenset()
objects, where set
objects cannot. set()
values are mutable and not hashable, frozenset()
values are immutable and are hashable.
They are to set
objects what tuple
objects are to list
objects.
Demo:
>>> s = set([1, 2])
>>> fs = frozenset(s)
>>> adict = {}
>>> adict[s] = 42 # a set as key does not work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> adict[fs] = 42 # a frozenset as key works
>>> s.add(s) # a set as value in a set does not work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> s.add(fs) # a frozenset as value in a set works
Recent Python versions will optimize the use of a set literal:
if somevar in {'foo', 'bar', 'baz'}:
by storing a frozenset()
constant with the bytecode:
>>> import dis
>>> dis.dis(compile("if somevar in {'foo', 'bar', 'baz'}: pass", '<stdin>', 'exec'))
1 0 LOAD_NAME 0 (somevar)
3 LOAD_CONST 4 (frozenset({'foo', 'baz', 'bar'}))
6 COMPARE_OP 6 (in)
9 POP_JUMP_IF_FALSE 15
12 JUMP_FORWARD 0 (to 15)
>> 15 LOAD_CONST 3 (None)
18 RETURN_VALUE
because the set literal cannot be mutated anyway; this makes using sets to test against very efficient. A regular set()
cannot be stored this way as that would allow you to mutate the constant stored with the byte object.
这篇关于frozenset() - 何时可以使用它们的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!