Перейти к основному содержимому

Python frozenset

frozenset — это неизменяемое множество: его нельзя изменить никогда.

Его элементы уникальны, неупорядочены и неизменяемы, как в обычном множестве.

Но добавлять или удалять их нельзя никогда.


Создание frozenset

Передайте любой итерируемый объект конструктору frozenset(), чтобы получить frozenset.

Пример

Создайте frozenset и проверьте его тип:

Prompt
Напишите программу на Python, которая демонстрирует код, показанный в примере PromptCookbook. x = frozenset({"apple", "banana", "cherry"}) print(x) print(type(x))
Вывод: полная программа на Python

Методы frozenset

Итак, добавлять и удалять элементы нельзя. Однако все операции множеств, которые не затрагивают данные, по-прежнему работают.

main.py
# Frozenset Methods
# Method        Shortcut    Description
# copy()                    Returns a shallow copy
# difference()  -           Returns a new frozenset with the difference
# intersection() &          Returns a new frozenset with the intersection
# isdisjoint()              Returns True if there is NO intersection between two frozensets
# issubset()    <= / <      Returns True if this frozenset is a (proper) subset of another
# issuperset()  >= / >      Returns True if this frozenset is a (proper) superset of another
# symmetric_difference() ^  Returns a new frozenset with the symmetric differences
# union()       |           Returns a new frozenset containing the union