【Python】Collection - set

Posted by 西维蜀黍 on 2019-10-20, Last Modified on 2023-08-26

Set

Python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交),difference(差)和sysmmetric 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