iOS開發人員如何學習Python程式設計8-集合型別3
這是我參與11月更文挑戰的8天,活動詳情檢視:2021最後一次更文挑戰。
Bytes
在Python3
以後,字串和bytes
型別徹底分開了:
- 字串
是以字元
為單位進行處理的。
- bytes
型別是以位元組
為單位處理的。
bytes
資料型別在所有的操作和使用甚至內建方法上和字串資料型別基本一樣,也是不可變的序列物件。
呼叫bytes()
生成bytes
例項。對於同一個字串如果採用不同的編碼方式生成bytes
物件,就會形成不同的值:
```
a = b'hello' type(a)
b = bytes('hello',encoding='utf8') type(b) ```
bytes
型別常用轉換
- 位元組轉成字串
```
d = b'world' d.decode() 'world' type(d)
```
- 字串轉為位元組
```
e = 'world' e.encode() b'world' type(e)
```
集合set
set集合
:無序不重複元素的集合,基本功能包括:
- 關係測試
- 消除重複元素
set
使用大括號{}
框定元素,並以逗號進行分隔: ⚠️注意:如果要建立一個空集合,必須用set()
而不是{}
,因為後者建立的是一個空字典。
```
s = {1,2,3} s {1, 2, 3} type(s)
s = {} # 注意,空的{}會預設為字典 type(s)
s = set() # 建立空集合->new empty set object(建立空集合) s set() type(s) s = set([1,2,3,1,2,3,4]) # 建立集合,去重 s {1, 2, 3, 4} s1 = set("hello world") # 建立集合,去重 s1 {'h', 'd', 'o', ' ', 'e', 'l', 'r', 'w'} s2 = set(123) # 注意,需要傳入可迭代的物件,而int型別的123並不是,所以報錯 Traceback (most recent call last): File "
", line 1, in TypeError: 'int' object is not iterable ```
集合新增元素
通過add(key)
方法可以新增元素到set
中,可以重複新增,但不會有效果:
```
s = set([1,2,3,1,2,3,4]) s {1, 2, 3, 4} s.add(3) # 重複新增,自動去重 s {1, 2, 3, 4} s.add(6) # 新增成功 s {1, 2, 3, 4, 6} s.add("cat") # 新增成功 s {1, 2, 3, 4, 6, 'cat'} s.add([1,2,3]) # 報錯,同字典一樣 不能新增可變物件 Traceback (most recent call last): File "
", line 1, in TypeError: unhashable type: 'list' ```
集合更新
可以通過update()
方法,將另一個物件更新到已有的集合中,這一過程同樣會進行去重:
```
s = set([1,2,3,4,5]) s.update("hello") # 將hello拆開放入集合 s {1, 2, 3, 4, 5, 'h', 'o', 'e', 'l'} s.update("hello") # 仍然去重 s {1, 2, 3, 4, 5, 'h', 'o', 'e', 'l'} ```
刪除元素
通過remove(key)
方法刪除指定元素,或者使用pop()
方法。注意,集合的pop
方法無法設定引數,刪除指定的元素:
set.remove()
```
s = {1, 2, 3, 4, 5, 'h', 'o', 'e', 'l'} s.remove(1) # 刪除該元素 s {2, 3, 4, 5, 'h', 'o', 'e', 'l'} s.remove('h') # 刪除該元素 s {2, 3, 4, 5, 'o', 'e', 'l'} s.remove('www') # 刪除不存在的元素則報錯 Traceback (most recent call last): File "
", line 1, in KeyError: 'www' ```
set.pop()
```
s1 = set("hello world") s1.pop() 'h' s1.pop() 'd' s1.pop() # 注意是隨機刪除 'o' s1.pop(1) # 不能通過索引刪除,因為本身無序 Traceback (most recent call last): File "
", line 1, in TypeError: pop() takes no arguments (1 given) ```
⚠️注意:集合不能取出某個元素,因為集合既不支援下標索引也不支援字典那樣的通過鍵值對獲取:
```
s1 {' ', 'e', 'l', 'r', 'w'} s1[1] Traceback (most recent call last): File "
", line 1, in TypeError: 'set' object does not support indexing ```