《Python编程的术与道:Python语言入门》视频课程
《Python编程的术与道:Python语言入门》视频课程链接:https://edu.csdn.net/course/detail/27845
frozenset
frozenset()
方法返回一个不可变的(immutable)frozenset对象,该对象使用给定iterable中的元素进行初始化。
冻结集合(Frozen set)只是Python集合对象的不可变版本。 一个集合的元素可以随时修改,但是冻结集合的元素在创建后保持不变。
因此,冻结集合可以用作Dictionary中的键或用作另一个集合的元素。 但是像集合一样,它也不是有序的。
frozenset()方法的语法为:
frozenset([iterable])
frozenset()参数
frozenset()方法可以选择使用单个参数:
iterable(可选)- 可迭代对象,它包含用于初始化frozenset的元素。可迭代对象可以是集合、字典、元组等。
frozenset()的返回值
frozenset()方法返回一个不可变的frozenset,它使用给定iterable中的元素进行初始化。
如果未传递任何参数,则返回一个空的frozenset。
Example 1:
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())
The frozen set is: frozenset({'a', 'o', 'i', 'e', 'u'})
The empty frozen set is: frozenset()
Example 2: frozenset() for Dictionary
当将字典用作冻结集合的可迭代对象时, 只使用字典的键来创建集合。
# random dictionary
person = {"name": "John", "age": 23, "sex": "male"}
fSet = frozenset(person)
print('The frozen set is:', fSet)
The frozen set is: frozenset({'age', 'name', 'sex'})
Example #3:
如果想更改frozenset对象,则会引发错误"‘frozenset’ object does not support item assignment".
# Python program to understand
# use of frozenset function
# creating a list
favourite_subject = ["OS", "Data Base", "Algorithm"]
# making it frozenset type
f_subject = frozenset(favourite_subject)
# below line will generate error
f_subject[1] = "Networking"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-821da7ec4ca4> in <module>
10 # below line will generate error
11
---> 12 f_subject[1] = "Networking"
TypeError: 'frozenset' object does not support item assignment