集合的定义与创建集合是一种数据结构,其中元素不重复且无顺序。在Python中,集合通常用于存储一组唯一元素。创建集合的语法为:`set() 或 set(iterable)`。例如,创建一个包含数字的集合:示例:`my_set = set([1, 2, 3, 4])`成员检测检查元素是否存在于集合中,使用`in`关键字。例如:示例:`if 3 in my_set:`集合常用方法1. add():向集合中添加一个元素。例如:示例:`my_set.add(5)`2. update():向集合中添加一个可迭代对象的元素。例如:示例:`my_set.update([6, 7])`3. remove():移除集合中的指定元素。例如:示例:`my_set.remove(5)`4. discard():如果元素存在于集合中,则移除该元素。若不存在,则不执行任何操作。例如:示例:`my_set.discard(8)`5. pop():随机移除集合中的一个元素。例如:示例:`my_set.pop()`6. clear():清空集合。例如:示例:`my_set.clear()`集合运算1. 交集运算:使用`intersection()`方法或操作符`&`。例如:示例:`intersection_set = my_set.intersection([1, 2, 3])` 或 `intersection_set = my_set & [1, 2, 3]`2. 并集运算:使用`union()`方法或操作符`|`。例如:示例:`union_set = my_set.union([4, 5, 6])` 或 `union_set = my_set | [4, 5, 6]`3. 差集运算:使用`difference()`方法或操作符`-`。例如:示例:`difference_set = my_set.difference([1, 2])` 或 `difference_set = my_set - [1, 2]`集合推导式集合推导式类似于列表推导式,用于创建新集合。例如:示例:`new_set = {x for x in range(1, 4)}`