Python 集合详解:定义、操作及示例
在 Python 中,集合 (set) 是一种无序且不重复的数据结构。集合可以用于存储多个元素,并且可以对集合进行交集、并集、差集等操作。
以下是一个示例,展示了如何创建和使用集合:
# 创建一个集合
fruits = {'apple', 'banana', 'orange'}
# 打印集合
print(fruits) # 输出: {'apple', 'banana', 'orange'}
# 检查集合中的元素
print('apple' in fruits) # 输出: True
print('grape' in fruits) # 输出: False
# 添加元素到集合
fruits.add('grape')
print(fruits) # 输出: {'apple', 'banana', 'orange', 'grape'}
# 从集合中移除元素
fruits.remove('banana')
print(fruits) # 输出: {'apple', 'orange', 'grape'}
# 集合的交集、并集、差集操作
fruits1 = {'apple', 'banana', 'orange'}
fruits2 = {'orange', 'grape'}
print(fruits1.intersection(fruits2)) # 输出: {'orange'}
print(fruits1.union(fruits2)) # 输出: {'apple', 'banana', 'orange', 'grape'}
print(fruits1.difference(fruits2)) # 输出: {'apple', 'banana'}
值得注意的是,集合中的元素是无序的,因此每次打印集合时元素的顺序可能会不同。此外,集合中的元素必须是不可变的,例如字符串、数字或元组,而不能包含可变的元素,如列表。
原文地址: https://www.cveoy.top/t/topic/bQcT 著作权归作者所有。请勿转载和采集!