Set介绍

1. set

无序,不重复序列。

学习思路:如何创建、有哪些功能

(1) 创建(两种创建方式):

a = {"123", "456"}

类比:元组转换为列表,使用 list()—>list __init__,内部执行for循环。相当于新创建了一个列表。

s = set()  # 创建空集合

li = [11,22,11,22]

s1 = set(li)  -->相当于执行for循环,新创建一个集合

(2) 功能:

s = set()

s.add(123)  #使用set添加,可自动去重复值

s.update()  # 可迭代的,如:列表、字符串、元组都可以,执行for循环不断的add

s1 = {11,22,33}

s2 = {22,33,44}
s3 = s1.difference(s2)
# A中存在,B中不存在

s1.symmetric_difference(s2)  # A中存在,B中不存在 + A中不存在,B中存在

   # 此时s1 s2 无变化

s1.difference_update(s2)  # 结果更新到s1中

s1 = {11,22,33}

s1.discard()  # 移除指定元素,不存在不报错

s1.remove()  # 移除元素,不存在报错

s1.pop()  # 随机移除

s1.intersection(s2)  # 取两个集合的交集

s1.intersection_update(s2)  # 取两个集合的交集,存于s1中

def isdisjoint(self, *args, **kwargs): # real signature unknown

""" Return True if two sets have a null intersection.  如果没有交集,返回True,否则返回False"""

pass

def issubset(self, *args, **kwargs): # real signature unknown

""" Report whether another set contains this set.  是否是子序列"""

pass

def issuperset(self, *args, **kwargs): # real signature unknown

""" Report whether this set contains another set. 是否是父序列"""

pass

实例:

old_dict = {
    "#1": 8,
    "#2": 4,
    "#4": 2,
}

new_dict = {
    "#1": 4,
    "#2": 4,
    "#3": 2,
}
# old_kyes = old_dict.keys()
# old_set = set(old_kyes)
new_set = set(new_dict.keys())
old_set = set(old_dict.keys())

remove_set = old_set.difference(new_set)  # 更新表的时候,删除谁
add_set = new_set.difference(old_set)  # 增加谁
update_set = old_set.intersection(new_set)  # 更新谁

原文地址:https://www.cnblogs.com/qpzm/p/5918028.html