Python 集合 set
阿新 • • 發佈:2019-02-12
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.