python-demo/basic/集合.py

51 lines
1.2 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@File : 集合.py.py
@Author : lichao
@Date : 2024/12/6 10:38
@Software : PyCharm
"""
# 集合是一个无序的、不重复的数据集合,列表是有序的,可以重复的数据集合
# 创建集合的两种方式
# 1.使用{}创建
set_data = {1, 2, 3, 4, 5}
print(type(set_data))
# 集合不能使用下标访问
# print(set_data[0]) # TypeError: 'set' object is not subscriptable
# 不能使用{}创建空集合,因为{}创建的是空字典
# set_data1 = {} # <class 'dict'>
set_data2 = set()
print(type(set_data2))
# 集合方法
# 1.添加元素
set_data2.add(1)
# 2.删除元素
set_data2.remove(1)
# 3.清空集合
set_data2.clear()
# 4.删除集合
del set_data2
# 5.集合的交集、并集、差集、对称差集
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 交集
print(set1 & set2) # {4, 5}
print(set1.intersection(set2)) # {4, 5}
# 并集
print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8}
print(set1.union(set2)) # {1, 2, 3, 4, 5, 6, 7, 8}
# 差集
print(set1 - set2) # {1, 2, 3}
print(set1.difference(set2)) # {1, 2, 3}
# 对称差集
print(set1 ^ set2) # {1, 2, 3, 6, 7, 8}
print(set1.symmetric_difference(set2)) # {1, 2, 3, 6, 7, 8}