本系列将会陆续整理分享一些的Python内置函数。
-
通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj
提取码:mnsj
-
前往GitHub获取:
https://github.com/returu/Python_built-in_functions
frozenset(iterable)
时,实际上是在创建f
r
ozenset
类的一个实例。作为一个类,它有自己的方法和属性,类似于其他数据结构(如 set
、list
、tuple
和 dict
)。https://docs.python.org/3/library/stdtypes.html#frozenset
frozenset(iterable=set())
-
iterable:可以是任何可迭代对象,例如列表、元组、字典、字符串等。
返回值:
下面是一些使用 frozenset() 函数的示例:
-
示例 1:基本使用
从可迭代对象创建frozenset对象。
# 创建空的 frozenset
empty_frozenset = frozenset()
print(empty_frozenset) # 输出:frozenset()
# 从集合创建 frozenset
my_set = {4, 5, 6}
frozenset_from_set = frozenset(my_set)
print(frozenset_from_set) # 输出: frozenset({4, 5, 6})
# 从列表创建 frozenset
my_list = [1, 2, 3, 4, 5]
frozenset_from_list = frozenset(my_list)
print(frozenset_from_list) # 输出:frozenset({1, 2, 3, 4, 5})
# 从字符串创建 frozenset
my_string = "hello"
frozenset_from_string = frozenset(my_string)
print(frozenset_from_string) # 输出:frozenset({'e', 'h', 'l', 'o'})
# 从字典创建 frozenset
my_dict = {"a": 1, "b": 2, "c": 3}
frozenset_from_dict = frozenset(my_dict)
print(frozenset_from_dict) # 输出:frozenset({'c', 'a', 'b'})
-
示例 2:不可变性示例
尝试修改frozenset会引发AttributeError。
# 尝试修改 frozenset 会导致错误
my_frozenset = frozenset([1, 2, 3])
my_frozenset.add(4)
# 报错:AttributeError: 'frozenset' object has no attribute 'add'
-
示例 3:使用场景
frozenset因其不可变性可用作字典的键或其他集合的元素。
# 作为字典的键
d = {frozenset([1, 2]): "value1", frozenset([3, 4]): "value2"}
print(d[frozenset([1, 2])]) # 输出: value1
# 作为集合的元素
s = {frozenset([1, 2]), frozenset([3, 4])}
print(s) # 输出: {frozenset({3, 4}), frozenset({1, 2})}


本篇文章来源于微信公众号: 码农设计师