Python 3 集合操作详解

作者:JC2024.04.02 20:58浏览量:3

简介:本文将详细介绍Python 3中集合(set)的各种操作,包括创建、添加、删除、交集、并集、差集、对称差集等操作,帮助读者更好地理解和使用集合。

Python 3 集合操作详解

在Python 3中,集合(set)是一种无序且不重复的数据结构,常用于去重、关系测试及集合运算等场景。本文将详细讲解Python 3中集合的各种操作,包括创建、添加、删除、交集、并集、差集、对称差集等。

创建集合

在Python 3中,可以使用大括号 {}set() 函数来创建集合。例如:

  1. # 使用大括号创建集合
  2. my_set1 = {1, 2, 3, 4}
  3. print(my_set1) # 输出:{1, 2, 3, 4}
  4. # 使用set()函数创建集合
  5. my_set2 = set([1, 2, 2, 3, 4, 4])
  6. print(my_set2) # 输出:{1, 2, 3, 4},注意集合中的元素不重复

添加元素

可以使用 add() 方法向集合中添加单个元素,或使用 update() 方法添加多个元素。例如:

  1. my_set = {1, 2, 3}
  2. # 使用add()方法添加单个元素
  3. my_set.add(4)
  4. print(my_set) # 输出:{1, 2, 3, 4}
  5. # 使用update()方法添加多个元素
  6. my_set.update([5, 6, 7])
  7. print(my_set) # 输出:{1, 2, 3, 4, 5, 6, 7}

删除元素

可以使用 remove() 方法删除集合中的单个元素,或使用 discard() 方法尝试删除元素(如果元素不存在则忽略)。此外,还可以使用 pop() 方法随机删除并返回一个元素,或使用 clear() 方法清空整个集合。例如:

  1. my_set = {1, 2, 3, 4, 5}
  2. # 使用remove()方法删除元素
  3. my_set.remove(3)
  4. print(my_set) # 输出:{1, 2, 4, 5}
  5. # 使用discard()方法尝试删除元素
  6. my_set.discard(6) # 忽略,因为6不在集合中
  7. print(my_set) # 输出:{1, 2, 4, 5}
  8. # 使用pop()方法随机删除并返回一个元素
  9. removed_element = my_set.pop()
  10. print(removed_element) # 输出:随机的一个元素,如5
  11. print(my_set) # 输出:{1, 2, 4}
  12. # 使用clear()方法清空集合
  13. my_set.clear()
  14. print(my_set) # 输出:set()

交集、并集、差集和对称差集

Python 3中的集合还支持多种集合运算,包括交集、并集、差集和对称差集。这些运算可以通过相应的操作符或方法来实现。例如:

```python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

交集:& 或 intersection() 方法

intersection = set1 & set2
print(intersection) # 输出:{3, 4}
intersection = set1.intersection(set2)
print(intersection) # 输出:{3, 4}

并集:| 或 union() 方法

union = set1 | set2
print(union) # 输出:{1, 2, 3, 4, 5, 6}
union = set1.union(set2)
print(union) # 输出:{1, 2, 3, 4, 5, 6}

差集:- 或 difference() 方法

difference = set1 - set2
print(difference) # 输出:{1, 2}
difference = set1.difference(set2)
print(difference) # 输出:{1, 2}

对称差集:^ 或 symmetric_difference() 方法

symmetric_difference = set1 ^ set2
print(symmetric_difference)