python利用集合的无重复性_python集合?
展開全部
*事先說明:以下代碼及結果來自本設備Python控制臺,在不同設備上可能32313133353236313431303231363533e59b9ee7ad9431333433643632結果有區別,望自己嘗試為妙
集合(set),是一種Python里的類(class),
集合類似于列表(list),可更改,可迭代(iterable),但是元素不重復
定義集合使用花括號{},例如:
>>> s = {"apple", "banana", "strawberry", "watermelon"}
警告!!!如果使用空括號
>>> a = {}
>>> a.__class__
a將成為一個字典
想要定義空集合,
請使用類名。
>>> a = set()
類名定義也可以把迭代轉換為集合:
>>> b = set("abc")
>>> b
{'a', 'b', 'c'}
但是,保存后它是無序的。
>>> s
{'banana', 'watermelon', 'strawberry', 'apple'}
(結果僅供參考,在不同設備上略有不同)
下面介紹它的性質:
1. 可更改:使用add(x)方法添加元素x:
>>> s.add("lemon")
>>> s
{'banana', 'strawberry', 'lemon', 'watermelon', 'apple'}使用update(iter1, iter2, …)方法添加多個可迭代對象(如列表,元組(tuple),另一個集合)里的元素:
>>> s.update(("orange", "grape"))
>>> s
{'banana', 'strawberry', 'orange', 'lemon', 'watermelon', 'apple', 'grape'}
警告!!!如果使用字符串,字符串也會被迭代:
>>> a = set()
>>> a.update("apple")
>>> a
{'a', 'p', 'e', 'l'}使用remove(x)移除元素x,如果x不存在,則拋出KeyError錯誤
>>> s.remove("lemon")
>>> s
{'banana', 'strawberry', 'orange', 'watermelon', 'apple', 'grape'}
>>> s.remove("cat")
Traceback (most recent call last):
File "", line 1, in
s.remove("cat")
KeyError: 'cat'使用discard(x)移除元素x,不會發生錯誤
>>> s.discard("grape")
>>> s
{'banana', 'strawberry', 'orange', 'watermelon', 'apple'}
>>> s.discard("dog")
>>> s
{'banana', 'strawberry', 'orange', 'watermelon', 'apple'}
2. 可迭代:
>>> for x in s:
...? ? print(x)
banana
strawberry
orange
watermelon
apple
3. 可以使用 len 函數獲取集合長度;
>>> len(s)
5
可以使用?in關鍵字檢查一個元素是否在集合內,將返回邏輯值(bool):
>>> "apple"? in s
True
>>> "candy" in s
False
4.集合具有不重復性,因此它會自動去重:
>>> c = set("Hello World!")
>>> c
{' ', 'e', 'l', 'H', '!', 'r', 'W', 'o', 'd'}
5. 集合的運算
>>> d = set("abcdef")
>>> e = set("efghij")
>>> d
{'c', 'e', 'a', 'b', 'f', 'd'}
>>> e
{'h', 'e', 'g', 'j', 'f', 'i'}
>>> d - e # 集合d去掉集合e含有的元素,或者說集合d包含而集合e不包含的元素(不改變原集合)
{'a', 'b', 'd', 'c'}
>>> d | e # 集合d,e的所有元素
{'c', 'e', 'h', 'g', 'a', 'b', 'j', 'f', 'd', 'i'}
>>> d & e # 集合d,e都包含的元素
{'f', 'e'}
>>> d ^ e # 不同時出現在集合d, e中的元素
{'c', 'g', 'h', 'a', 'b', 'j', 'd', 'i'}
注意!!!
字符串、列表通用的+和*不適用于集合
>>> "abc" + "def"
'abcdef'
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> d + e
Traceback (most recent call last):
File "", line 1, in
d + e
TypeError: unsupported operand type(s) for +: 'set' and 'set'
>>> "a" * 5
'aaaaa'
>>> [1] * 3
[1, 1, 1]
>>> d*3
Traceback (most recent call last):
File "", line 1, in
d * 2
TypeError: unsupported operand type(s) for *: 'set' and 'int'
(作者的小觀點:既然集合是不能重復的,那么乘以、重復是沒有意義的)
總結
以上是生活随笔為你收集整理的python利用集合的无重复性_python集合?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 硬件模拟大师_科普丨硬件检测软件3D M
- 下一篇: python定时关闭进程_Python子