zoukankan      html  css  js  c++  java
  • 集合

    # 集合 { } 由不同元素(会去重)组成的集合,无序的
    # 可添加删除,不可修改(如果使用 s=frozenset('hello'),则不可变)
    # 只能存放不可变类型(数字,字符串,元组)
    
    # 定义方式1
    s = {1, 2, 3, 'hello', (0, 8)}
    # 定义方式2(使用可迭代对象)
    s = set(['hello', 'world'])
    
    # for循环
    for i in s:
        print(i)
    
    # in 操作
    print(2 in s)
    print(2 not in s)
    
    # 添加一个值
    s.add('ok')
    
    # 清空
    s.clear()
    
    # copy,浅拷贝
    s1 = s.copy()
    
    # 随机删除
    s.pop()
    
    # 指定删除, 不存在则报错
    s.remove('ok')
    
    # 指定删除, 不存在不会报错
    s.discard('ok')
    
    
    
    
    # 集合关系运算
    python_l = ['lcg', 'szw', 'zjw']
    linux_l = ['lcg', 'szw', 'sb']
    p_s = set(python_l)
    l_s = set(linux_l)
    # 交集
    print(p_s.intersection(l_s))   # 或者使用&
    print(p_s & l_s)
    # intersection_update 参考差集的difference_update
    
    # 并集
    print(p_s.union(l_s))  # 或者使用|
    print(p_s | l_s)
    # update 参考差集的difference_update
    
    # 差集 (存在于左边的集合,不存在于右边的集合)
    print(p_s.difference(l_s))  # 或者使用-
    print(p_s - l_s)
    # 求完差集后将结果更新至左边的集合
    p_s.difference_update(l_s)
    print(p_s)  # 等同于
    p_s = p_s - l_s
    
    # 交叉补集 (将两个集合合在一起减去它们共有的部分)
    print(p_s.symmetric_difference(l_s))  # 或者使用^
    print(p_s ^ l_s)
    # symmetric_difference_update 参考差集的difference_update
    
    # 判断两个集合是否有交集 没有返回True 有返回False
    print(p_s.isdisjoint(l_s))
    
    # 判断左边的集合是否是右边集合的子集 是返回True 不是返回False
    print(p_s.issubset(l_s))  # 或者使用<=
    print(p_s <= l_s)
    
    # 判断左边的集合是否是右边集合的父集 是返回True 不是返回False
    print(p_s >= l_s)  # 或者使用>=
  • 相关阅读:
    luogu 1865 数论 线性素数筛法
    洛谷 2921 记忆化搜索 tarjan 基环外向树
    洛谷 1052 dp 状态压缩
    洛谷 1156 dp
    洛谷 1063 dp 区间dp
    洛谷 2409 dp 月赛题目
    洛谷1199 简单博弈 贪心
    洛谷1417 烹调方案 dp 贪心
    洛谷1387 二维dp 不是特别简略的题解 智商题
    2016 10 28考试 dp 乱搞 树状数组
  • 原文地址:https://www.cnblogs.com/dangrui0725/p/9410570.html
Copyright © 2011-2022 走看看