set1 = {1, 'alex', 'barry', 3, 5}
print(set1)
增:
set1 = {'太白金星', '晶女神', 'alex', '吴老师'}
add
set1.add('ss')
print(set1) #{'吴老师', '太白金星', 'alex', '晶女神', 'ss'}
update #跌带着增加
set1.update('yuanhao123')
print(set1) #{'alex', 'a', '晶女神', '3', 'o', 'n', '太白金星', '吴老师', 'h', '2', '1', 'y', 'u'}
删
remove 按照元素删除
set1.remove('alex')
print(set1) #{'太白金星', '晶女神', '吴老师'}
pop 随机删除
set1.pop()
print(set1) #第一次{'alex', '晶女神', '吴老师'} 第二次{'太白金星', 'alex', '吴老师'}
变相该值
set1.remove('太白金星')
set1.add('男神')
print(set1) #{'alex', '晶女神', '吴老师', '男神'}
交集
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 & set2) #{4, 5}
并集
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set2 | set1) {1, 2, 3, 4, 5, 6, 7, 8}
差集
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 - set2) #{1, 2, 3}
print(set2 - set1) #{8, 6, 7}
反交集
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 ^ set2) #{1, 2, 3, 6, 7, 8}
子集与超集
set1 = {1,2,3}
set2 = {1,2,3,4,5,6}
print(set1.issubset(set2)) #True #这两个相同,都是说明set1是set2子集
print(set1 < set2) # 这两个相同,都是说明set1是set2子集
print(set2 > set1) #这两个相同,都是说明set2是set1超集
面试题
l1 = [1, 2, 2, 1, 3, 5, 6, 8, 8, 9]
l2 = list(set(l1))
print(l2) #[1, 2, 3, 5, 6, 8, 9]