GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.runoob.com — Python3 集合 | 菜鸟教程
Python 3 教程
Python3 教程
Python3 简介
Python3 环境搭建
Python3 Pycharm
Python3 VScode
Python3 基础语法
Python3 基本数据类型
Python3 数据类型转换
Python3 解释器
Python3 注释
Python3 运算符
Python3 数字(Number)
Python3 字符串
Python3 列表
Python3 元组
Python3 字典
Python3 集合
Python3 条件控制
Python3 循环语句
Python3 编程第一步
Python3 推导式
Python3 迭代器与生成器
Python3 with
Python3 函数
Python3 lambda
Python3 装饰器
Python3 数据结构
Python3 模块
Python __name__
Python3 输入和输出
Python3 File
Python3 OS
Python3 错误和异常
Python3 面向对象
Python3 命名空间/作用域
Python 虚拟环境的创建
Python 类型注解
Python3 标准库概览
Python3 实例
Python 测验
Python3 高级教程Python3 正则表达式 Python3 CGI编程 Python3 MySQL(mysql-connector) Python3 MySQL(PyMySQL) Python3 网络编程 Python3 SMTP发送邮件 Python3 多线程 Python3 XML 解析 Python3 JSON Python3 日期和时间 Python3 内置函数 Python3 MongoDB Python3 urllib Python uWSGI 安装配置 Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python 有用的资源 Python AI 绘画 Python statistics Python hashlib Python 量化 Python pyecharts Python selenium 库 Python 爬虫 Python Scrapy 库 Python Markdown Python sys 模块 Python Pickle 模块 Python subprocess 模块 Python queue 模块 Python StringIO 模块 Python logging 模块 Python datetime 模块 Python re 模块 Python csv 模块 Python threading 模块 Python asyncio 模块 Python PyQtPython3 集合集合(Set)是 Python 中的一种内置容器类型,用于存储多个不重复的元素。 集合具有以下特点:
集合常用于数据去重、成员判断以及多个数据集合之间的比较。 创建集合可以使用大括号 语法格式: set_name = {value1, value2, value3}
set_name = set(iterable)
例如: 实例
# 使用大括号创建集合
set1 = {1, 2, 3, 4} # 使用 set() 从列表创建集合 set2 = set([4, 5, 6, 7]) # 从字符串创建集合 set3 = set("hello") print(sorted(set1)) print(sorted(set2)) print(sorted(set3)) 执行结果: [1, 2, 3, 4] [4, 5, 6, 7] ['e', 'h', 'l', 'o'] 可以看到, 注意:创建空集合必须使用 empty_set = set() # 空集合
empty_dict = {} # 空字典
print(type(empty_set))
print(type(empty_dict))
执行结果: <class 'set'> <class 'dict'> 集合自动去重集合中的元素不会重复,因此可以利用 实例
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers) print(sorted(unique_numbers)) 执行结果: [1, 2, 3, 4, 5] 需要注意,转换为集合后,原有元素的排列顺序不会得到保证。 如果需要对列表去重并保留原有顺序,可以使用: numbers = [3, 1, 2, 3, 2, 4] result = list(dict.fromkeys(numbers)) print(result) 执行结果: [3, 1, 2, 4] 上述保序去重方法要求元素可以作为字典键使用,适用于 Python 3.7 及以上版本。 集合元素的类型限制集合中的元素必须是可哈希(Hashable)的对象。 常见的可哈希对象包括整数、浮点数、字符串,以及所有成员都可哈希的元组。 my_set = {1, 3.14, "Python", (1, 2)}
print(len(my_set))
执行结果: 4 列表、字典和普通集合通常不可哈希,不能直接作为集合元素。 my_set = {[1, 2], [3, 4]}
# TypeError: unhashable type: 'list'
如果需要将一个集合作为另一个集合的元素,可以使用不可变集合 集合运算Python 集合支持数学中常见的集合运算,例如并集、交集、差集和对称差集。 假设有两个集合: a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
常见运算符如下:
实例
a = {1, 2, 3, 4}
b = {3, 4, 5, 6} # 并集 print("并集:", sorted(a | b)) # 交集 print("交集:", sorted(a & b)) # 差集 print("差集:", sorted(a - b)) # 对称差集 print("对称差集:", sorted(a ^ b)) 执行结果: 并集: [1, 2, 3, 4, 5, 6] 交集: [3, 4] 差集: [1, 2] 对称差集: [1, 2, 5, 6] 说明:差集具有方向性, 除了运算符,还可以使用集合方法: a.union(b) a.intersection(b) a.difference(b) a.symmetric_difference(b) 这些方法返回新的集合,不会直接修改原集合。 集合运算符通常要求两个操作数是集合类型;对应的方法则可以根据具体方法接受列表、元组等可迭代对象。 集合推导式与列表推导式类似,Python 也支持集合推导式(Set Comprehension),可以使用简洁的语法创建集合。 基本语法: {expression for item in iterable if condition}
其中, 实例
# 生成 1 到 5 的平方集合
squares = {x * x for x in range(1, 6)} print(sorted(squares)) # 过滤字符串中的指定字符 letters = { x for x in "abracadabra" if x not in "abc" } print(sorted(letters)) 执行结果: [1, 4, 9, 16, 25] ['d', 'r'] 集合推导式也会自动去除重复元素。 集合的基本操作1、添加元素可以使用 语法格式: s.add(x) 如果元素已经存在,集合不会发生变化,也不会报错。 实例
thisset = {"Google", "Runoob", "Taobao"}
thisset.add("Facebook") thisset.add("Google") # 已存在,不会重复添加 print(sorted(thisset)) 执行结果: ['Facebook', 'Google', 'Runoob', 'Taobao'] 如果需要一次添加多个元素,可以使用 语法格式: s.update(iterable1, iterable2, ...)
实例
thisset = {1, 2, 3}
# 添加列表中的元素 thisset.update([4, 5]) # 同时添加多个可迭代对象中的元素 thisset.update((6, 7), {8, 9}) print(sorted(thisset)) 执行结果: [1, 2, 3, 4, 5, 6, 7, 8, 9] 注意:如果向 s = {1, 2}
s.update({"a": 10, "b": 20})
print(sorted(s, key=str))
输出结果: [1, 2, 'a', 'b'] 如果想添加字典的值,可以使用 2、移除元素集合提供了 remove() 方法
语法格式: s.remove(x) 实例
thisset = {"Google", "Runoob", "Taobao"}
thisset.remove("Taobao") print(sorted(thisset)) # 以下操作会引发 KeyError thisset.remove("Facebook") 执行结果: ['Google', 'Runoob'] Traceback (most recent call last): ... KeyError: 'Facebook' discard() 方法
语法格式: s.discard(x) 实例
thisset = {"Google", "Runoob", "Taobao"}
thisset.discard("Facebook") # 不存在,不报错 thisset.discard("Taobao") print(sorted(thisset)) 执行结果: ['Google', 'Runoob'] pop() 方法
语法格式: s.pop() 实例
thisset = {"Google", "Runoob", "Taobao", "Facebook"}
# 移除一个元素 removed = thisset.pop() print("移除的元素属于原集合:", removed in {"Google", "Runoob", "Taobao", "Facebook"}) print("剩余元素个数:", len(thisset)) 执行结果: 移除的元素属于原集合: True 剩余元素个数: 3 注意: 如果集合为空,调用 删除方法对比
3、计算集合元素个数可以使用 语法格式: len(s) 实例
thisset = {"Google", "Runoob", "Taobao"}
print(len(thisset)) thisset.add("Google") print(len(thisset)) 执行结果: 3 3 因为集合不会保存重复元素,所以再次添加 4、清空集合可以使用 语法格式: s.clear() 实例
thisset = {"Google", "Runoob", "Taobao"}
thisset.clear() print(thisset) print(len(thisset)) 执行结果: set() 0 这里输出的 5、判断元素是否在集合中可以使用 语法格式: x in s x not in s 实例
thisset = {"Google", "Runoob", "Taobao"}
print("Runoob" in thisset) print("Facebook" in thisset) print("Facebook" not in thisset) 执行结果: True False True 集合通常基于哈希表实现,因此成员判断在一般情况下具有较高效率,平均时间复杂度通常为 O(1),但最坏情况下可能退化。 6、判断子集、超集和不相交集合除了并集、交集等运算,Python 还支持判断两个集合之间的包含关系。 常见方法如下:
实例
a = {1, 2}
b = {1, 2, 3, 4} c = {5, 6} print(a.issubset(b)) print(b.issuperset(a)) print(a.isdisjoint(c)) # 也可以使用比较运算符 print(a <= b) # 子集 print(a < b) # 真子集 print(b >= a) # 超集 执行结果: True True True True True True
不可变集合 frozenset除了普通集合 两者都具有元素不重复、无固定顺序等特点,但 可以使用 实例
a = frozenset([1, 2, 3, 3])
print(sorted(a)) print(type(a)) # frozenset 支持集合运算 b = frozenset([3, 4, 5]) print(sorted(a | b)) print(sorted(a & b)) 执行结果: [1, 2, 3] <class 'frozenset'> [1, 2, 3, 4, 5] [3]
由于 nested_set = {
frozenset({1, 2}),
frozenset({3, 4})
}
print(len(nested_set))
执行结果: 2 普通的 集合使用注意事项在使用 Python 集合时,需要注意以下几点:
如果需要将集合中的元素按固定顺序显示,可以使用 集合内置方法完整列表以下整理了 Python 集合常用的内置方法。
注意: 另外,以 总结Python 集合主要用于存储不重复的数据,并支持高效的成员判断和常见集合运算。 在实际开发中,集合最常见的用途包括:
如果需要按照索引访问数据,或者需要保留元素的插入顺序,通常应该优先考虑列表等其他数据结构;如果需要去重、集合运算或快速成员判断,则可以优先考虑集合。
AI 思考中...
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |