Python set


python的set和其他語言類似, 是一個無序不重復元素集, 基本功能包括關系測試和消除重復元素. 集合對象還支持union(聯合), intersection(交), difference(差)和sysmmetric difference(對稱差集)等數學運算.

基本操作

 s={1,2,"a"}

 type(s)

set

x=set("python") x {'h', 'n', 'o', 'p', 't', 'y'} y=set(["y","a",1]) y {1, 'a', 'y'} #去重 a=[1,1,2,2,3,3] b=set(a) b {1, 2, 3} y.add(2) y.add("hello") {1, 2, 'a', 'hello', 'y'} #從 set “s”中刪除元素 , 如果不存在則引發 KeyError y.remove("hello") y.remove(2) {1, 'a', 'y'} #如果在 set “s”中存在元素 x, 則刪除 y.discard(1) #刪除並且返回 set “y”中的一個不確定的元素, 如果為空則引發 KeyError y.pop() #刪除 set “y”中的所有元素並保留set y.clear() y set() y.update([3,4,5]) {1, 3, 4, 5, 'a', 'y'} len(y) 6 "x" in y False #測試是否 s 中的每一個元素都在 t 中 x=y #測試是否 y 中的每一個元素都在 x 中,即 x包含y x=y y.issubset(x) y<=x #測試是否 x 中的每一個元素都在 y中,即y包含x y.issuperset(x) y>=x #返回一個新的 set 包含 x 和 y 中的每一個元素 x=set("python1") y.union(x) x|y #返回一個新的 set 包含 x 和 y 中的公共元素 y.intersection(x) x&y #返回一個新的 set 包含 y 中有但是 x 中沒有的元素 y.difference(x) y-x #返回一個新的 set 包含 x 和 y 中不重復的元素 y.symmetric_difference(x) y^x #set y的一個淺復制 z=y.copy()

dir(set)

['__and__',
'__class__',
'__cmp__',
'__contains__',
'__delattr__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__iand__',
'__init__',
'__ior__',
'__isub__',
'__iter__',
'__ixor__',
'__le__',
'__len__',
'__lt__',
'__ne__',
'__new__',
'__or__',
'__rand__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__ror__',
'__rsub__',
'__rxor__',
'__setattr__',
'__sizeof__',
'__str__',
'__sub__',
'__subclasshook__',
'__xor__',
'add',
'clear',
'copy',
'difference',
'difference_update',
'discard',
'intersection',
'intersection_update',
'isdisjoint',
'issubset',
'issuperset',
'pop',
'remove',
'symmetric_difference',
'symmetric_difference_update',
'union',
'update']

 

 help(set.add)

 Help on method_descriptor:

 add(...)
 Add an element to a set.
 This has no effect if the element is already present.

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM