📜  Python Frozenset()

📅  最后修改于: 2020-09-20 04:05:12             🧑  作者: Mango

Frozenset() 函数返回一个不变的Frozenset对象,该对象使用给定的iterable中的元素初始化。

冻结集只是Python集对象的不可变版本。尽管可以随时修改集合的元素,但是冻结集合的元素在创建后保持不变。

因此,冻结的集可以用作Dictionary中的键或另一个集的元素。但是像集合一样,它也不是有序的(可以在任何索引处设置元素)。

frozenset() 函数的语法为:

frozenset([iterable])

Frozenset()参数

frozenset() 函数采用一个参数:

  1. iterable(可选)-可迭代,它包含用于初始化Frozenset的元素。可以设置Iterable,Dictionary,Tuple等。

从Frozenset()返回值

frozenset() 函数返回一个不变的frozenset ,并使用给定iterable中的元素进行初始化。

如果未传递任何参数,则返回一个空的frozenset

示例1: Python Frozenset()的工作

# 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())

# frozensets are immutable
fSet.add('v')

输出

The frozen set is: frozenset({'a', 'o', 'u', 'i', 'e'})
The empty frozen set is: frozenset()
Traceback (most recent call last):
  File ", line 8, in 
    fSet.add('v')
AttributeError: 'frozenset' object has no attribute 'add'

示例2:Dictionary的frozenset()

当您将字典用作冻结集合的可迭代对象时,它仅需要字典的键来创建集合。

# random dictionary
person = {"name": "John", "age": 23, "sex": "male"}

fSet = frozenset(person)
print('The frozen set is:', fSet)

输出

The frozen set is: frozenset({'name', 'sex', 'age'})

Frozenset操作

像普通集一样,Frozenset也可以执行不同的操作,例如copydifferenceintersectionsymmetric_differenceunion

# Frozensets
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])

# copying a frozenset
C = A.copy()  # Output: frozenset({1, 2, 3, 4})
print(C)

# union
print(A.union(B))  # Output: frozenset({1, 2, 3, 4, 5, 6})

# intersection
print(A.intersection(B))  # Output: frozenset({3, 4})

# difference
print(A.difference(B))  # Output: frozenset({1, 2})

# symmetric_difference
print(A.symmetric_difference(B))  # Output: frozenset({1, 2, 5, 6})

输出

frozenset({1, 2, 3, 4})
frozenset({1, 2, 3, 4, 5, 6})
frozenset({3, 4})
frozenset({1, 2})
frozenset({1, 2, 5, 6})

同样,也可以使用其他设置方法,例如isdisjointissubsetissuperset

# Frozensets
# initialize A, B and C
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
C = frozenset([5, 6])

# isdisjoint() method
print(A.isdisjoint(C))  # Output: True

# issubset() method
print(C.issubset(B))  # Output: True

# issuperset() method
print(B.issuperset(C))  # Output: True

输出

True
True
True