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'
    '''
    

      

      

  • 相关阅读:
    JS判断字符串是否为空或是否全为空格
    分页-jquery.page.js插件在使用时重复触发“上一页”和“下一页”操作
    JS IE 打开本地exe程序
    bootstrap中的模态框(modal,弹出层)
    attr()、prop()、css() 的区别
    java-ActiveMQ
    java-webSocket
    java-普通类文件@Autowired自动注入为null
    HTML5<canvas>标签:使用canvas元素在网页上绘制四分之一圆(3)
    HTML5<canvas>标签:使用canvas元素在网页上绘制渐变和图像(2)
  • 原文地址:https://www.cnblogs.com/alamZ/p/7152948.html
Copyright © 2011-2022 走看看