zoukankan      html  css  js  c++  java
  • python学习-20 集合

                               集合set

    1.由不同元素组成的集合,集合是一组无序排列的,集合中的元素必须是不可变的

    -定义集合

    第一种:

    jh = {1,2,3,4}
    print(type(jh),jh)

    运行结果:

    <class 'set'> {1, 2, 3, 4}
    
    Process finished with exit code 0

    第二种:

    jh = set('hello')
    print(type(jh),jh)

    运行结果:

    <class 'set'> {'e', 'o', 'h', 'l'}
    
    Process finished with exit code 0

    -添加元素

    jh = {1,2,3,4}
    jh.add("nihao")
    print(jh)
    {1, 2, 3, 4, 'nihao'}
    
    Process finished with exit code 0

    -删除

    *.clear  清除集合

    *.pop  随机删除

    jh = {1,2,3,4}
    jh.pop()
    print(jh)

    运行结果:

    {2, 3, 4}
    
    Process finished with exit code 0

    *.remove 删除指定元素(如果指定的元素不在,会报错)

    jh = {1,2,3,4}
    jh.remove(4)
    print(jh)

    运行结果:

    {1, 2, 3}
    
    Process finished with exit code 0

    *.discard   删除指定元素(如果指定元素不在,不会报错)

    -交集 &

    math = {'xm','xh','xg'}
    english ={'xm','xh'}
    
    print(math.intersection(english))

    运行结果:

    {'xh', 'xm'}
    
    Process finished with exit code 0

    -并集 |

    math = {'xm','xh','xg','xx'}
    english ={'xm','xh','dm','john'}
    
    print(math.union(english))

    运行结果:

    {'xg', 'dm', 'john', 'xm', 'xx', 'xh'}
    
    Process finished with exit code 0

    -差集(也可以两个集合做减法)

    math = {'xm','xh','xg','xx'}
    english ={'xm','xh','dm','john'}
    
    print(math.difference(english))
    print(english.difference(math))

    运行结果:

    {'xg', 'xx'}
    {'dm', 'john'}
    
    Process finished with exit code 0
  • 相关阅读:
    Linq聚合操作之Aggregate,Count,Sum,Distinct源码分析
    Linq分区操作之Skip,SkipWhile,Take,TakeWhile源码分析
    Linq生成操作之DefautIfEmpty,Empty,Range,Repeat源码分析
    Linq基础操作之Select,Where,OrderBy,ThenBy源码分析
    PAT 1152 Google Recruitment
    PAT 1092 To Buy or Not to Buy
    PAT 1081 Rational Sum
    PAT 1084 Broken Keyboard
    PAT 1077 Kuchiguse
    PAT 1073 Scientific Notation
  • 原文地址:https://www.cnblogs.com/liujinjing521/p/11112793.html
Copyright © 2011-2022 走看看