frozenset()是Python的内置函数,它将可迭代对象作为输入并使它们不变。简单地,它冻结了可迭代的对象并使它们不可更改。
在Python中,Frozenset与set相同,除了它的元素是不可变的。此函数将输入作为任何可迭代对象,并将它们转换为不可变对象。不能保证元素的顺序被保留。
用法: frozenset(iterable_object_name)
参数:该函数接受可迭代对象作为输入参数。
返回类型:此函数返回一个等效的Frozenset对象。
下面的示例对此进行了清晰的解释。
范例1:
如果没有参数传递给frozenset()
函数,然后返回一个空的Frozenset类型对象。
# 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)
输出:
frozenset Object is: frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})
范例2:用途frozenset()
。
由于Frozenset对象是不可变的,因此它们主要用作字典或其他集合元素中的键。下面的示例清楚地说明了这一点。
# 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:警告
如果由于错误而我们想更改Frozenset对象,则会引发错误“'frozenset'对象不支持项目分配”。
# 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
相关用法
注:本文由纯净天空筛选整理自ankit15697大神的英文原创作品 frozenset() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。