集合怎么写

用花括号,和字典区分(字典有冒号):

fruits = {"苹果", "橘子", "苹果", "香蕉"}
print(fruits)      # {'苹果', '橘子', '香蕉'}  自动去重

空集合必须用 set()——{} 是空字典:

empty_set = set()       # 对
empty_dict = {}         # 对
empty = {}              # 这是字典不是集合!

集合的特点

  • 元素不重复(自动去重)
  • 无序(不能用下标访问 s[0] 会报错)
  • 元素必须可哈希(list / dict 不能放进去,tuple / str / int 可以)

增删

s = {1, 2, 3}
s.add(4)           # {1, 2, 3, 4}
s.update([5, 6])   # {1, 2, 3, 4, 5, 6}
s.remove(3)        # 删除,不存在会 KeyError
s.discard(99)      # 删除,不存在不报错
s.pop()            # 随机弹出一个

集合运算(数学集合)

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

a | b      # {1,2,3,4,5,6}    并集 union
a & b      # {3, 4}           交集 intersection
a - b      # {1, 2}           差集 difference
a ^ b      # {1, 2, 5, 6}     对称差(只在一方)

也可用方法名:a.union(b) / a.intersection(b) / 等。

实战:去重一个列表

nums = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(nums))    # [1, 2, 3, 4]

注意:去重后顺序丢了。要保留顺序:

seen = set()
result = []
for n in nums:
    if n not in seen:
        seen.add(n)
        result.append(n)
# result: [1, 2, 3, 4]

或用 dict(Python 3.7+ 字典保序):

result = list(dict.fromkeys(nums))    # [1, 2, 3, 4]

成员检查比 list 快很多

huge = list(range(1_000_000))
huge_set = set(huge)

999_999 in huge       # 慢:O(n),要扫一遍
999_999 in huge_set   # 快:O(1),哈希查找

下一篇进入条件判断 if