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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。