Python Tutorials

Python集合:完整指南

Spread the love

Python中的集合是无序的唯一元素集合。这意味着重复的值会自动消除,添加元素的顺序不会影响它们的存储或检索方式。集合默认情况下是可变的(可更改的),除非您使用frozenset类型,它是不可变的。

集合对于需要高效成员测试(检查元素是否存在)、从列表中删除重复项以及执行集合运算(如并集、交集和差集)的任务特别有用。

目录

  1. 创建集合
  2. 添加和更新元素
  3. 删除元素
  4. 集合运算
  5. 集合方法
  6. 其他集合运算
  7. 集合的内置函数
  8. 冻结集合

1. 创建集合

您可以使用花括号{}set()构造函数创建集合。请注意,空集合必须使用set()创建;{}创建的是空字典。


# 使用花括号
my_set = {1, 2, 3, 4, 5}
print(my_set)  # 输出:{1, 2, 3, 4, 5}

# 使用set()构造函数
another_set = set([6, 7, 8, 8])  # 重复项会自动删除
print(another_set)  # 输出:{8, 6, 7}

empty_set = set()
print(empty_set)  # 输出:set()

请记住,集合是无序的,因此输出顺序可能与输入顺序不同。

2. 添加和更新元素

使用add()方法添加单个元素,使用update()方法添加多个元素。


my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # 输出:{1, 2, 3, 4}

my_set.update([5, 6, 7])
print(my_set)  # 输出:{1, 2, 3, 4, 5, 6, 7}

my_set.update({8, 9}, (10,))  # 使用集合和元组更新
print(my_set)  # 输出:{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

3. 删除元素

几种方法允许删除元素。如果找不到元素,remove()会引发KeyError,而discard()不会。


my_set = {1, 2, 3, 4, 5}

my_set.remove(3)  # 如果元素不存在,则引发KeyError
print(my_set)  # 输出:{1, 2, 4, 5}

my_set.discard(6)  # 如果元素不存在,则不会引发错误
print(my_set)  # 输出:{1, 2, 4, 5}

removed_element = my_set.pop()  # 删除并返回任意一个元素
print(removed_element)  # 输出:(一个随机元素)
print(my_set)

my_set.clear()  # 删除所有元素
print(my_set)  # 输出:set()

4. 集合运算

集合支持标准的数学集合运算:


set1 = {1, 2, 3}
set2 = {3, 4, 5}

# 并集:组合两个集合中的元素
union_set = set1 | set2  # 或 set1.union(set2)
print(union_set)  # 输出:{1, 2, 3, 4, 5}

# 交集:两个集合中都存在的元素
intersection_set = set1 & set2  # 或 set1.intersection(set2)
print(intersection_set)  # 输出:{3}

# 差集:在set1中但在set2中不存在的元素
difference_set = set1 - set2  # 或 set1.difference(set2)
print(difference_set)  # 输出:{1, 2}

# 对称差集:在set1或set2中,但并非两者都存在的元素
symmetric_difference_set = set1 ^ set2  # 或 set1.symmetric_difference(set2)
print(symmetric_difference_set)  # 输出:{1, 2, 4, 5}

5. 集合方法

Python提供了许多用于集合操作的内置方法:


my_set = {1, 2, 3, 4, 5}

print(my_set.issubset({1, 2, 3, 4, 5, 6}))  # True
print(my_set.issuperset({1, 2}))  # True
print(my_set.isdisjoint({6, 7, 8}))  # True - 没有共同元素
print(my_set.copy()) # 创建集合的浅拷贝

6. 其他集合运算

除了基本运算之外,您还可以检查成员资格、查找长度等等:


my_set = {1, 2, 3}
print(1 in my_set)  # 输出:True
print(4 not in my_set)  # 输出:True
print(len(my_set))  # 输出:3

7. 集合的内置函数

all()any()sum()min()max()等函数可用于集合:


my_set = {1, 2, 3, 4, 5}
print(sum(my_set))  # 输出:15
print(min(my_set))  # 输出:1
print(max(my_set))  # 输出:5
print(all(x > 0 for x in my_set))  # 输出:True
print(any(x == 0 for x in my_set))  # 输出:False

8. 冻结集合

frozenset创建一个不可变集合。创建后,您无法添加或删除元素。它们可用作字典键或其他集合的元素。


my_frozenset = frozenset({1, 2, 3})
# my_frozenset.add(4)  # 这将引发AttributeError
print(my_frozenset)  # 输出:frozenset({1, 2, 3})

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注