程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python frozenset collection

編輯:Python

List of articles

  • Python frozenset aggregate


Python frozenset aggregate

set A set is a variable sequence , The program can change the elements in the sequence ;frozenset A set is an immutable sequence , The program cannot change the elements in the sequence .set All the methods in a set that can change the set itself , such as remove()、discard()、add() etc. ,frozenset Don't support ;set A method in a set that does not change the set itself ,fronzenset All support .

We can enter... In an interactive programming environment dir(frozenset) Check it out. frozenset Collection support methods :

>>> dir(frozenset)
['copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', 'symmetric_difference', 'union']

frozenset These methods and methods of collection set The function of the method with the same name in the collection is the same .

In two cases, you can use fronzenset:

  1. When the elements of the set do not need to be changed , We can use fronzenset replace set, It's safer .
  2. Sometimes programs require immutable objects , Also use this time fronzenset replace set. such as , Dictionaries (dict) Key (key) It is required to be an immutable object .

The following program demonstrates frozenset Usage of :

s = {
'Python', 'C', 'C++'}
fs = frozenset(['Java', 'Shell'])
s_sub = {
'PHP', 'C#'}
# towards set Add... To the collection frozenset
s.add(fs)
print('s =', s)
# for set Add child to collection set aggregate 
s.add(s_sub)
print('s =', s)

Running results :

s = {
'Python', frozenset({
'Java', 'Shell'}), 'C', 'C++'}
Traceback (most recent call last):
File "C:\Users\mozhiyan\Desktop\demo.py", line 11, in <module>
s.add(s_sub)
TypeError: unhashable type: 'set'

It should be noted that ,set The elements of the collection itself must be immutable , therefore set The element of cannot be set, Can only be frozenset. The first 6 Line code to set Add frozenset No problem , because frozenset It's immutable ; however , The first 10 In line of code, try to set Add to the cake set, This is not allowed , because set Is variable .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved