• 14、set集合


    无序集合、不允许有重赋元素

    #创建集合
    s = set([1,2,3,4,5,3])
    print(s) #{1, 2, 3, 4, 5}
    
    #添加元素
    s.add(7)
    print(s) #{1, 2, 3, 4, 5, 7}
    s.add(1)
    print(s) #{1, 2, 3, 4, 5, 7}
    
    #清空集合
    s.clear()
    print(s) #set()
    
    #在s1中查询s2中元素,去掉查询到的元素,剩下的创建一个新的集合
    s1 = set([1,2,3,4,5])
    s2 = set([4,5,6,7,8])
    s3 = s1.difference(s2)
    print(s3) #{1, 2, 3}
    
    #在s1中查询s2中元素,去掉查询到的元素
    s1 = set([1,2,3,4,5])
    s2 = set([4,5,6,7,8])
    s1.difference_update(s2)
    print(s1) #{1, 2, 3}
    
    #如果是集合元素刚删除,如果不是则不操作
    s1 = set([1,2,3,4,5])
    s1.discard(1)
    print(s1) #{2, 3, 4, 5}
    
    #返回两个集合的交集,并创建一个新的集合
    s1 = set([1,2,3,4,5])
    s2 = set([4,5,6,7,8])
    s3 = s1.intersection(s2)
    print(s3) #{4, 5}
    
    #用s2来更新s1,找出来个集合中相同的部分
    s1 = set([1,2,3,4,5])
    s2 = set([4,5,6,7,8])
    s1.intersection_update(s2)
    print(s1) #{4, 5}
    
    #判断两个集合是否有交集,如有则返回False,没有则返回True
    s1 = set([1,2,3,4,5])
    s2 = set([4,5,6,7,8])
    s4 = set([0,9])
    s3 = s1.isdisjoint(s2)
    print(s3) #False
    s5 = s1.isdisjoint(s4)
    print(s5) #True
    
    #判断一个集合是否包含另一集合,如果包含则返回True,否则返回False
    s1 = set([1,2,3,4,5])
    s2 = set([4,5])
    s4 = set([1,0,9])
    s3 = s2.issubset(s1)
    print(s3) #True
    s5 = s4.issubset(s1)
    print(s5) #False
    
    #判断一个集合是否包含另一集合,如果包含则返回True,否则返回False
    s1 = set([1,2,3,4,5])
    s2 = set([4,5])
    s4 = set([1,0,9])
    s3 = s1.issubset(s1)
    print(s3) #True
    s5 = s1.issubset(s4)
    print(s5) #False
    
    #删除元素,并返回被删除的元素
    s = set([1,2,3,4,5,6])
    print(s.pop()) # 1
    print(s) #{2, 3, 4, 5, 6}
    
    #删除指定成员元素
    s = set([1,2,3,4,5,6])
    print(s.remove(1)) # None
    print(s) #{2, 3, 4, 5, 6}
  • 相关阅读:
    Gym
    HDU-2680 Choose the best route 单向边+反向dijkstra
    Hdu1010Tempter of the Bone 深搜+剪枝
    CodeForces
    CodeForces
    Gym-101375C MaratonIME eats japanese food 初始化struct技巧
    Gym
    java was started but returned exit code =-805306369的处理方法
    启动myeclipse弹窗Please allow Subclipse team to receive anonymous usage statistics for this Eclipse intance
    eclipse包分层
  • 原文地址:https://www.cnblogs.com/jp-mao/p/6293173.html
Copyright © 2020-2023  润新知