Python 集合 set

python set 集合

set 集合是一种数据类型

set跟list一样可以用{}来定义,但是pyton -v 版本 >2.7

set的数据格式:

s1={"abc","def"}      #{} 自己定义
>>> print s1
set(['abc', 'def'])  
>>> s2=set("abcdef")  #set 函数用string进行初始化
>>> print s2
set(['a', 'c', 'b', 'e', 'd', 'f'])
>>> s3=set(["abc",123,"def"])  #set 函数用list进行初始化
>>> print s3
set([123, 'abc', 'def'])

结合set的基本方法

 |  add(...)        #set 后面追加一个element
 |      Add an element to a set.  
 |      
 |      This has no effect if the element is already present.
 |  
 |  clear(...)
 |      Remove all elements from this set.
 |  
 |  copy(...)
 |      Return a shallow copy of a set.
 |  
 |  difference(...)   #s3.difference(s4)  #s3 跟s4 不同的element 组成一个新的set 
 |      Return the difference of two or more sets as a new set.
 |      
 |      (i.e. all elements that are in this set but not the others.)
 |  
 |  difference_update(...)    
 |      Remove all elements of another set from this set.
 |    
  >>> print s4
set(['abc', 'def', 'ghk'])   
>>> s3={"abc",123,"def"}
>>> s3.difference(s4)  #之前的s3 s4 都不变,会把s3 中有,s4中没有的数据打印出来组成一个新的set
set([123])
>>> print s3
set([123, 'abc', 'def'])
>>> print s4
set(['abc', 'def', 'ghk'])

>>> s3.difference_update(s4)  #s3 直接是上面的结果,s4 不变化
>>> print s3
set([123])
>>> print s4
set(['abc', 'def', 'ghk'])


 |  discard(...)
 |      Remove an element from a set if it is a member.
 |      
 |      If the element is not a member, do nothing.
 |  
 |  intersection(...)  #交集
 |      Return the intersection of two or more sets as a new set.
 |      
 |      (i.e. elements that are common to all of the sets.)
 |  
 |  intersection_update(...)
 |      Update a set with the intersection of itself and another.
 |  
 |  isdisjoint(...)
 |      Return True if two sets have a null intersection.
 |  
 |  issubset(...)
 |      Report whether another set contains this set.
 |  
 |  issuperset(...)
 |      Report whether this set contains another set.
 |  
 |  pop(...)
 |      Remove and return an arbitrary set element.
 |      Raises KeyError if the set is empty.
 |  
 |  remove(...)
 |      Remove an element from a set; it must be a member.
 |      
 |      If the element is not a member, raise a KeyError.


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值