# Python set 示例代码
# 创建一个空的集合
empty_set = set()
print("空集合:", empty_set)
# 创建一个包含元素的集合
fruits = {"apple", "banana", "cherry"}
print("水果集合:", fruits)
# 添加元素到集合中
fruits.add("orange")
print("添加元素后的水果集合:", fruits)
# 移除集合中的元素
fruits.remove("banana")
print("移除元素后的水果集合:", fruits)
# 集合的交集操作
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection = set1.intersection(set2)
print("交集:", intersection)
# 集合的并集操作
union = set1.union(set2)
print("并集:", union)
# 集合的差集操作
difference = set1.difference(set2)
print("差集 (set1 - set2):", difference)
set()
:用于创建一个空的集合。add()
:用于向集合中添加元素。remove()
:用于从集合中移除指定元素,如果元素不存在会抛出错误。intersection()
:返回两个集合的交集。union()
:返回两个集合的并集。difference()
:返回两个集合的差集(即第一个集合中有但第二个集合中没有的元素)。上一篇:python str 转json
下一篇:input在python中用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站