Set
Sets are a recent addition to the language that are neither mappings nor sequences; rather, they are unordered collections of unique and immutable objects. You create sets by calling the built-in set function or using new set literals and expressions in 3.X and 2.7, and they support the usual mathematical set operations (the choice of new {…} syntax for set literals makes sense, since sets are much like the keys of a valueless dic-tionary):
>>> X = set('spam') # Make a set out of a sequence in 2.X and 3.X
>>> Y = {'h', 'a', 'm'} # Make a set with set literals in 3.X and 2.7
>>> X, Y # A tuple of two sets without parentheses
({'m', 'a', 'p', 's'}, {'m', 'a', 'h'})
>>> X & Y # Intersection
{'m', 'a'}
>>> X | Y # Union
{'m', 'h', 'a', 'p', 's'}
>>> X - Y # Difference
初始化
s = set([3,5,9,10]) #创建一个数值集合
t = set("Hello") #创建一个唯一字符的集合
基本操作
t.add('x') # 添加一项
s.update([10,37,42]) # 在s中添加多项
# 使用remove()可以删除一项:
t.remove('H')
# set 的长度
len(s)
# 测试 x 是否是 s 的成员
x in s
# 测试 x 是否不是 s 的成员
x not in s
# 测试是否 s 中的每一个元素都在 t 中
s.issubset(t)
s <= t
# remove an elementi
mixture = {"a", "b", 1, 2, 3}
# after running this line
# mixture no longer contains "a"
mixture.discard("a")
# sort
a = ("b", "g", "a", "d", "f", "c", "h", "e")
sorted(a) # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
集合运算
>>> x & y # 交集
set(['a', 'm'])
>>> x | y # 并集
set(['a', 'p', 's', 'h', 'm'])
>>> x - y # 差集
set(['p', 's'])
# equal
nums = {10, 20, 30, 40, 50}
other_nums = {30, 10, 50, 40, 20}
other_nums == nums # returns True
nums == {20, 30} # returns False
# union
nums = {10}
others = {60, 70, 80}
combined = nums.union(others) # {10,60,70,80}
# inteerscetion
nums.intersection(others)
# difference
# We can get the difference between two sets (i.e. what elements exist in one set, but not the other) using the difference method.
nums = {10, 20, 30, 40, 50}
others = {60, 70, 80}
nums.difference(others)
# subet
sample = {"a", "c"}
letters = {'a', 'b', 'c'}
sample.issubset(letters) # returns True
sample.issubset(nums) # returns False
Reference
- Python Crash Course (2nd Edition) : A Hands-On, Project-Based Introduction to Programming
- Learning Python