PYTHON set 集合學習

2022-06-05 21:00:08 字數 1904 閱讀 2498

#建立乙個空的集合必須用set(),因為{}為dict。且set()只接受乙個引數

>>> a ={}

>>>type(a)

'dict

'>

>>> a =set()

>>>type(a)

'set

'>

>>>

#集合中放的只能是數字、元組、字串,不能放字典,列表

>>> set1 = 

traceback (most recent call last):

file

"", line 1, in

set1 =

typeerror: unhashable type:

'list

'>>> set1 =

>>>set1

>>> set1 = }

traceback (most recent call last):

file

"", line 1, in

set1 = }

typeerror: unhashable type:

'dict

'

#但是單個的字典、集合、列表還是可以的

>>> a = set([1,2,3])

>>>a

>>> a = set()

>>>a

>>> a = set()

>>>a

#組合起來就不行了

>>> a = set()

traceback (most recent call last):

file

"", line 1, in

a = set()

typeerror: unhashable type:

'list

'>>> a = set()

traceback (most recent call last):

file

"", line 1, in

a = set()

typeerror: unhashable type:

'list

'>>>

2.1 列表過濾:

#可以將列表中的重複元素過濾掉,很簡單的

>>> a = [1,1,1,2,3,6,5,8,6,2]

>>>set(a)

>>>list(set(a))

[1, 2, 3, 5, 6, 8]

2.2 add(值)

>>> c = 

>>> c.add(2)

>>>c

#增肌愛元素的無序性,就是沒加在最後

>>> c.add(2)

>>>c

#互異性

2.3 remove(值)

>>>c

>>> c.remove(2)

>>>c

>>> c.remove(5)

traceback (most recent call last):

file

"", line 1, in

c.remove(5)

keyerror: 5

>>>

2.4 集合運算:

>>> a = 

>>> b =

>>> a &b #交集

>>> a |b #並集

>>> a -b #a中a&b的補集

>>> b -a #b中a&b的補集

>>>

Python set集合詳解

python 中的集合,和數學中的集合概念一樣,用來儲存不重複的元素,即集合中的元素都是唯一的,互不相同。從形式上看,和字典類似,python 集合會將所有元素放在一對大括號 中,相鄰元素之間用 分隔,如下所示 其中,elementn 表示集合中的元素,個數沒有限制。從內容上看,同一集合中,只能儲存...

python set集合基礎

python set 基礎 集合 set 是乙個無序的不重複元素序列。可以使用大括號 或者 set 函式建立集合,注意 建立乙個空集合必須用 set 而不是 因為 是用來建立乙個空字典 a 1 2,3 4,1 print set a 結果 hello set hello.add b print he...

python set集合操作

set集合是乙個無序且不重複的集合。建立乙個set集合 name set sdd name 返回結果 add 功能 增加集合元素 name name.add d name 返回結果 name.add sd name 返回結果 clear 功能 清空集合元素 name name.clear name ...