zoukankan      html  css  js  c++  java
  • python 集合set remove update add

    1.

    集合(set):把不同的元素组成一起形成集合,是python基本的数据类型。

    集合对象是一组无序排列hashable value:集合成员可以做字典的键。

    集合就像是 list 和 dict 的组合。

    #coding:utf8
    
    a=['h','e','l','l','o']
    
    a=set(a)
    b=set('welcome')
    
    print " a = " ,a
    print " b = " ,b
    print " 并集 ",a.union(b)  #a|b  #并集
    print " 并集 ",a|b  #并集
    print '*'*30
    print " 交集 ",a.intersection(b) #交集
    print " 交集 ",a&b  #交集
    print '*'*30
    print " 差集 ",b-a  #差集
    print " 差集 ",b.difference(a)   #差集
    print " 差集 ",a-b
    print '*'*30
    print " 对称差集 ",a^b  #对称差集
    print " 对称差集 ",a.symmetric_difference(b)  #对称差集
    '''
     a =  set(['h', 'e', 'l', 'o'])
     b =  set(['c', 'e', 'm', 'l', 'o', 'w'])
     并集  set(['c', 'e', 'h', 'm', 'l', 'o', 'w'])
     并集  set(['c', 'e', 'h', 'm', 'l', 'o', 'w'])
    ******************************
     交集  set(['e', 'l', 'o'])
     交集  set(['e', 'l', 'o'])
    ******************************
     差集  set(['c', 'm', 'w'])
     差集  set(['c', 'm', 'w'])
     差集  set(['h'])
    ******************************
     对称差集  set(['c', 'w', 'h', 'm'])
     对称差集  set(['c', 'w', 'h', 'm'])
    '''
    

     2.添加 删除 set

    #coding:utf8
    
    a=set('hello')
    print a
    
    a=set('hello')
    a.update("asdf")
    
    print 'a.update("asdf") ',a
    
    a=set('hello')
    a.add("asdf")
    
    print 'a.add("asdf") ',a
    
    a.pop()  #随机删除了一个
    print a
    
    a.discard('p')#当集合中没有这个元素的时候,不会报错
    a.remove('t') #当集合中没有这个元素的时候报错
    '''
    set(['h', 'e', 'l', 'o'])
    a.update("asdf")  set(['a', 'e', 'd', 'f', 'h', 'l', 'o', 's'])
    a.add("asdf")  set(['h', 'asdf', 'e', 'l', 'o'])
    set(['asdf', 'e', 'l', 'o'])
        a.remove('t') #当集合中没有这个元素的时候报错
    Traceback (most recent call last):
      File "D:AlamTWstudypython20170711.py", line 20, in <module>
    KeyError: 't'
    '''
    

      

      

  • 相关阅读:
    pip安装flask问题解决
    GRE新东方推荐学习方法(2010年左右)
    使用eclipse IDE遇到的问题
    2014年互联网大会(商业价值,北京,7月)
    Indexing the World Wide Web: the Journey So Far阅读笔记
    Big Data Opportunities and Challenges(by周志华)论文要点
    spark常用算子总结
    使用Faster R-CNN做目标检测
    Oracle 性能调优 SQL_TRACE
    Oracle 性能调优 10053事件
  • 原文地址:https://www.cnblogs.com/alamZ/p/7152948.html
Copyright © 2011-2022 走看看