tags = {"python", "docs"}
tags.add("beginner")
print(tags)
tags.update(["seo", "tutorial", "python"]) # adds multiple, ignores dupes
print(tags)
tags.remove("seo") # raises KeyError if the item isn't there
tags.discard("missing") # same as remove, but silent if not present
print(tags)
popped = tags.pop() # removes and returns an arbitrary item
print("popped:", popped, "remaining:", tags)
这正是集合真正大显身手的地方。无论集合有多大,x in some_set 都是常数时间。x in some_list 则必须逐个遍历列表,列表很大时就会变慢。
# Imagine this list has 1,000,000 items.
known_users = set(range(1_000_000))
# Each check is near-instant.
for user_id in [42, 999_999, 1_000_001]:
if user_id in known_users:
print(f"{user_id}: known")
else:
print(f"{user_id}: unknown")
经验法则:只要你发现自己在循环里写 if x in some_list,而列表又有几十个以上的元素,就先把列表转换成集合。
集合运算
这是集合真正有趣的地方。你可以用与数学集合运算相对应的运算符来组合它们:
frontend = {"html", "css", "javascript", "react"}
backend = {"python", "sql", "javascript", "docker"}
# Union: everything from both.
all_skills = frontend | backend
print(all_skills)
# Intersection: what's in both.
shared = frontend & backend
print(shared)
# Difference: in frontend but not backend.
only_frontend = frontend - backend
print(only_frontend)
# Symmetric difference: in one or the other, but not both.
unique_skills = frontend ^ backend
print(unique_skills)
known = {"python", "bash", "sql"}
required = {"python", "bash"}
print(required.issubset(known)) # True - required is inside known
print(known.issuperset(required)) # True
print(required <= known) # same as issubset, with an operator
print(known >= required) # same as issuperset