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.


你可能感兴趣的:(Python 集合 set)