Python Frozenset()

时间:2020-02-23 14:42:43  来源:igfitidea点击:

Python Frozenset是不同哈希对象的无序集合。
Frozenset是一个不可变的集合,因此其内容在创建后就无法修改。

Python Frozenset()

Python Frozenset()函数用于创建Frozenset对象。
其语法为:

class frozenset([iterable])

如果提供了输入的iterable参数,则从iterable元素创建forzenset。
如果未提供任何参数,则返回一个空的Frozenset对象。

Python Frozenset()示例

让我们看看如何使用Frozenset()函数创建Frozenset对象。

fs = frozenset()
print(fs)
print(type(fs))

# frozenset from iterable
list_vowels = ['A', 'E', 'I', 'O', 'U']
fs = frozenset(list_vowels)
print(fs)

tuple_numbers = (1, 2, 3, 4, 5, 4, 3)
fs = frozenset(tuple_numbers)
print(fs)

输出:

frozenset()
<class 'frozenset'>
frozenset({'E', 'U', 'I', 'O', 'A'})
frozenset({1, 2, 3, 4, 5})

迭代Frozenset元素

我们可以使用for循环迭代冻结的set元素。

fs = frozenset([1, 2, 3, 4, 5, 4, 3])
for x in fs:
  print(x)

输出:

1
2
3
4
5

请注意,在创建Frozenset时,将删除重复的元素。

Python Frozenset函数

由于Frozenset是不可变的,因此没有可用的方法来更改其元素。
因此,add(),remove(),update(),pop()等函数没有为frozenset定义。

让我们看一下Frozenset对象可用的一些方法。

  • len(fs):返回冻结集中的元素数量。

  • x in fs:如果x存在于fs中,则返回True,否则返回False。

  • x not in fs:如果x在fs中不存在,则返回True,否则返回False。

  • isdisjoint(other):如果Frozenset与其他元素没有共同点,则返回True。
    当且仅当两个交集为空集时,两个集才是不相交的。

  • issubset(other):如果该集合中的每个元素都存在于另一个集合中,则返回True,否则返回False。

  • issuperset(other):如果集合中存在其他元素,则返回True,否则返回False。

  • " union(* others)":返回一个新的Frozenset对象,其中包含来自Frozenset和其他集合的元素。

  • intersection(* others):返回一个新的Frozenset,其中包含该集合以及所有其他集合中的元素。

  • difference(* others):返回一个新的frozenset,其中frozenset中的元素不在其他集中。

  • " symmetric_difference(other)":返回一个新的frozenset,其中包含处于frozenset或者其他但非两个都包含的元素。

fs = frozenset([1, 2, 3, 4, 5])

size = len(fs)
print('frozenset size =', size)

contains_item = 5 in fs
print('fs contains 5 =', contains_item)

not_contains_item = 6 not in fs
print('fs not contains 6 =', not_contains_item)

is_disjoint = fs.isdisjoint(frozenset([1, 2]))
print(is_disjoint)

is_disjoint = fs.isdisjoint(frozenset([10, 20]))
print(is_disjoint)

is_subset = fs.issubset(set([1, 2]))
print(is_subset)

is_subset = fs.issubset(set([1, 2, 3, 4, 5, 6, 7]))
print(is_subset)

is_superset = fs.issuperset(frozenset([1, 2]))
print(is_superset)

is_superset = fs.issuperset(frozenset([1, 2, 10]))
print(is_superset)

fs1 = fs.union(frozenset([1, 2, 10]), set([99, 98]))
print(fs1)

fs1 = fs.intersection(set((1, 2, 10, 20)))
print(fs1)

fs1 = fs.difference(frozenset([1, 2, 3]))
print(fs1)

fs1 = fs.symmetric_difference(frozenset([1, 2, 10, 20]))
print(fs1)

fs1 = fs.copy()
print(fs1)

输出:

frozenset size = 5
fs contains 5 = True
fs not contains 6 = True
False
True
False
True
True
False
frozenset({1, 2, 3, 4, 5, 98, 99, 10})
frozenset({1, 2})
frozenset({4, 5})
frozenset({3, 20, 4, 5, 10})
frozenset({1, 2, 3, 4, 5})

Python Frozenset列出,元组

我们可以使用内置函数轻松地从Frozenset对象创建列表和元组。

fs = frozenset([1, 2, 3, 4, 5])
l1 = list(fs)
print(l1)

t1 = tuple(fs)
print(t1)

输出:

[1, 2, 3, 4, 5]
(1, 2, 3, 4, 5)