Python中的集合函数及其用法有哪些?
Python中的集合函数及其用法有很多,以下列举一些常用的集合函数及其用法:
1. set()
- 创建一个空集合或从其他可迭代对象创建一个集合。
- 例如:s = set()或s = set([1, 2, 3])
2. add(element)
- 向集合中添加一个元素。
- 例如:s.add(4)
3. remove(element)
- 从集合中移除指定元素。
- 如果元素不存在,会引发KeyError异常。
- 例如:s.remove(3)
4. discard(element)
- 从集合中移除指定元素,如果该元素不存在,则不会引发异常。
- 例如:s.discard(3)
5. pop()
- 随机从集合中移除并返回一个元素。
- 如果集合为空,会引发KeyError异常。
- 例如:s.pop()
6. clear()
- 清空集合中的所有元素。
- 例如:s.clear()
7. copy()
- 创建并返回集合的浅拷贝。
- 例如:s2 = s.copy()
8. len()
- 返回集合中元素的个数。
- 例如:l = len(s)
9. in 和 not in
- 判断某个元素是否在集合中。
- 例如:if 1 in s:或if 1 not in s:
10. issubset(other)
- 判断当前集合是否为另一个集合的子集。
- 例如:s.issubset(other)
11. issuperset(other)
- 判断当前集合是否为另一个集合的超集。
- 例如:s.issuperset(other)
12. union(other)
- 返回两个集合的并集,生成一个新的集合。
- 例如:s3 = s.union(other)
13. intersection(other)
- 返回两个集合的交集,生成一个新的集合。
- 例如:s4 = s.intersection(other)
14. difference(other)
- 返回两个集合的差集,生成一个新的集合(仅包含当前集合的元素)。
- 例如:s5 = s.difference(other)
15. symmetric_difference(other)
- 返回两个集合的对称差集,生成一个新的集合(仅包含不在两个集合中共同的元素)。
- 例如:s6 = s.symmetric_difference(other)
16. update(other)
- 将当前集合更新为与另一个集合的并集。
- 例如:s.update(other)
17. intersection_update(other)
- 将当前集合更新为与另一个集合的交集。
- 例如:s.intersection_update(other)
18. difference_update(other)
- 将当前集合更新为与另一个集合的差集(仅包含当前集合的元素)。
- 例如:s.difference_update(other)
19. symmetric_difference_update(other)
- 将当前集合更新为与另一个集合的对称差集(仅包含不在两个集合中共同的元素)。
- 例如:s.symmetric_difference_update(other)
这些是常用的集合函数及其用法。集合是一种无序且不重复的元素集,在实际的编程中非常有用,可以方便地进行集合运算和元素的添加、移除等操作。
