python學習十一 set集合

2021-08-14 15:00:35 字數 2644 閱讀 7183

set集合

特點:無序

元素不重複(可以用於海量資料去重)

功能關係測試

去重******************************====

python的set和其他語言類似, 是乙個無序不重複元素集, 基本功能包括關係測試和消除重複元素. 

集合物件還支援union(聯合), intersection(交), difference(差)和sysmmetric difference(對

稱差集)等數**算. 

******************************====

>>> name_set = set([1,2,4,5])

>>> type(name_set)

>>> name_set

set([1, 2, 4, 5])                集合型別

>>> name_set = set([1,2,4,5,2])

>>> name_set

set([1, 2, 4, 5])      這裡並沒有新加的2,天然去重複

>>> a = range(10)

>>> a

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> a = set(a)             把列表變成集合型別

>>> type(a)

不支援索引

>>> a[1]

traceback (most recent call last):

file "", line 1, in

typeerror: 'set' object does not support indexing  不支援索引

新增資料

>>> a.add(1)

>>> a

set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> a.add(100)

>>> a

set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100])

>>> a.add(-1) 

>>> a

set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, -1])

刪除資料

>>> a.pop()

0>>> a

set([1, 2, 3, 4, 5, 6, 7, 8, 9, 100, -1])

>>> a.pop()

1>>> a

set([2, 3, 4, 5, 6, 7, 8, 9, 100, -1])

-------------------------

測試x、y的關係

>>> x = set([1,2,3,4])

>>> y = set([3,4,5,6])

交集(x.intersection(y))

>>> x & y

set([3, 4])

並集(x.union(y))

>>> x | y

set([1, 2, 3, 4, 5, 6])

差集(x.difference(y))

>>> x - y    x裡存在,y裡不存在

set([1, 2])

對稱差集(反差集)(x.symmetric_difference(y))     他倆都有的去掉,都沒有的合到一塊

>>> x ^ y

set([1, 2, 5, 6])

子集(z.issubset(x))

>>> x,y  都不完全包含

(set([1, 2, 3, 4]), set([3, 4, 5, 6]))

>>> z = set([1,2,4])

>>> z.issubset(x)

true

父集(z.issuperset(x))

>>> z.issuperset(x)

false

******************************===

集合新增、刪除

python 集合的新增有兩種常用方法,分別是add和update。

集合add方法:是把要傳入的元素做為乙個整個新增到集合中,例如:

>>> a = set('boy')

>>> a.add('python')

>>> a

set(['y', 'python', 'b', 'o'])

集合update方法:是把要傳入的元素拆分,做為個體傳入到集合中,例如:

>>> a = set('boy')

>>> a.update('python')

>>> a

set(['b', 'h', 'o', 'n', 'p', 't', 'y'])

集合刪除操作方法:remove

set(['y', 'python', 'b', 'o'])

>>> a.remove('python')

>>> a

set(['y', 'b', 'o'])

******************************===

sets 支援 x in set, len(set),和 for x in set。作為乙個無序的集合,sets不記錄元素位置

或者插入點。因此,sets不支援 indexing, slicing, 或其它類序列(sequence-like)的操作。

python學習 集合set

num type num num2 type num2 這兩個大括號的型別明顯不一樣 num的型別是字典而num2的型別則是集合 集合集合具有唯一性 num2 num2 集合不會列印重複的東西 集合不支援索引 num2 2 traceback most recent call last file l...

Python基礎入門(十一) 集合set

1 什麼是set 1 與dict 字典 區別 dict的作用是建立一組 key 和一組 value 的對映關係,dict的key是不能重複的。set 持有一系列元素,這一點和 list 很像,但是set的元素沒有重複,而且是無序的,這點和 dict 的 key很像。2 建立 set 的方式 呼叫 s...

python學習之集合set

python學習之集合set 集合 set 是乙個無序的不重複的元素序列 if name main 1 建立集合 1 parame 2 set value set中只能有乙個引數 注 建立乙個空集合必須用set 而不是 因為 用來建立乙個空字典 print n1 建立集合 socket set ba...