📜  Python中的frozenset()

📅  最后修改于: 2022-05-13 01:55:45.711000             🧑  作者: Mango

Python中的frozenset()

freezeset()是Python中的一个内置函数,它接受一个可迭代对象作为输入并使它们不可变。简单地说,它冻结了可迭代对象并使它们不可更改。

在Python中,frozenset 与 set 相同,只是 freezeset 是不可变的,这意味着 freezeset 中的元素一旦创建就不能添加或删除。此函数将输入作为任何可迭代对象并将它们转换为不可变对象。不保证保留元素的顺序。

下面的例子清楚地解释了它。

示例 #1:
如果没有参数传递给 freezeset()函数,则它返回一个空的 freezeset 类型对象。

Python3
# Python program to understand frozenset() function
 
# tuple of numbers
nu = (1, 2, 3, 4, 5, 6, 7, 8, 9)
 
# converting tuple to frozenset
fnum = frozenset(nu)
 
# printing details
print("frozenset Object is : ", fnum)


Python3
# Python program to understand use
# of frozenset function
 
# creating a dictionary
Student = {"name": "Ankit", "age": 21, "sex": "Male",
           "college": "MNNIT Allahabad", "address": "Allahabad"}
 
# making keys of dictionary as frozenset
key = frozenset(Student)
 
# printing keys details
print('The frozen set is:', key)


Python3
# Python program to understand
# use of frozenset function
 
# creating a list
favourite_subject = ["OS", "DBMS", "Algo"]
 
# making it frozenset type
f_subject = frozenset(favourite_subject)
 
# below line will generate error
 
f_subject[1] = "Networking"


输出:
frozenset Object is :  frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})


示例 #2:frozenset() 的使用
由于frozenset 对象是不可变的,它们主要用作字典中的键或其他集合的元素。下面的例子清楚地解释了它。

Python3

# Python program to understand use
# of frozenset function
 
# creating a dictionary
Student = {"name": "Ankit", "age": 21, "sex": "Male",
           "college": "MNNIT Allahabad", "address": "Allahabad"}
 
# making keys of dictionary as frozenset
key = frozenset(Student)
 
# printing keys details
print('The frozen set is:', key)
输出:
The frozen set is: frozenset({'sex', 'age', 'address', 'name', 'college'})

示例 #3:警告
如果我们错误地想要更改freezeset对象,则会引发错误“ 'frozenset' object does not support item assignment ”。

Python3

# Python program to understand
# use of frozenset function
 
# creating a list
favourite_subject = ["OS", "DBMS", "Algo"]
 
# making it frozenset type
f_subject = frozenset(favourite_subject)
 
# below line will generate error
 
f_subject[1] = "Networking"

输出:

Traceback (most recent call last):
  File "/home/0fbd773df8aa631590ed0f3f865c1437.py", line 12, in 
    f_subject[1] = "Networking"
TypeError: 'frozenset' object does not support item assignment