答案頁 · 12 道題

Python collections練習答案

本頁彙整 Python collections 的 12 道練習。先做練習頁,再回到這裡核對準確答案和原因。

快速答案

本答案頁包含 Python collections 的 4 道選擇題、4 道填空題和 4 道輸出預測題,每題都給出準確答案和簡短解釋。

答案已完整展示,建議先嘗試作答,再用本頁核對。第一次練習最好從互動練習頁開始。

01 · 選擇題

Counter(votes) 回傳什麼?

  1. 值到次數的映射正確答案
  2. 排序後的值列表
  3. 值組成的元組
  4. 唯一值的集合

答案: 值到次數的映射

為什麼: Counter 是字典子類,值表示出現次數。

02 · 選擇題

這段程式列印出什麼?

from collections import Counter
print(Counter("aba")["a"])
  1. 3
  2. 0
  3. 1
  4. 2正確答案

答案: 2

為什麼: 字串裡有兩個 a;缺失的鍵才會回傳零。

03 · 選擇題

存取缺失鍵時,defaultdict(list) 會做什麼?

  1. 建立一個空列表正確答案
  2. 回傳 None
  3. 刪除鍵
  4. 拋出 KeyError

答案: 建立一個空列表

為什麼: list 工廠提供預設值,並把這個鍵插入字典。

04 · 選擇題

哪個 deque 方法會刪除最左邊的元素?

  1. pop()
  2. shift()
  3. removeleft()
  4. popleft()正確答案

答案: popleft()

為什麼: popleft 刪除並回傳雙端佇列左端的元素。

05 · 填空題

補全計數容器的匯入。

from collections import ____
print(Counter(["a", "a"]))

答案: Counter

為什麼: Counter 是 collections 中的計數字典。

06 · 填空題

補全回傳最高頻項的方法。

from collections import Counter
counts = Counter(["a", "b", "a"])
print(counts.____(1))

答案: most_common

為什麼: most_common 按次數從高到低回傳條目。

07 · 填空題

補全列表型 defaultdict 的工廠。

from collections import defaultdict
groups = defaultdict(____)

答案: list

為什麼: 傳入 list 會為缺失鍵建立空列表。

08 · 填空題

補全刪除隊首元素的方法。

from collections import deque
queue = deque([1, 2])
queue.____()

答案: popleft

為什麼: popleft 從雙端佇列左端刪除元素。

09 · 輸出預測

程式碼的輸出結果是什麼?

from collections import Counter
print(Counter("abca")["a"])

答案: 2

為什麼: 字元 a 出現了兩次。

10 · 輸出預測

螢幕上會顯示什麼?

from collections import Counter
print(Counter([1, 1, 2]).most_common(1))

答案: [(1, 2)]

為什麼: 出現最多的是 1,次數為 2。

11 · 輸出預測

這段程式碼會輸出什麼?

from collections import defaultdict
d = defaultdict(list)
d["x"].append(1)
print(dict(d))

答案: {'x': [1]}

為什麼: 缺失鍵得到空列表,然後被追加一個元素。

12 · 輸出預測

執行結果是什麼?

from collections import deque
q = deque([1, 2, 3])
q.popleft()
print(list(q))

答案: [2, 3]

為什麼: popleft 刪除第一個元素,剩下二和三。

先試一遍題目

打開 Python collections 練習頁,用即時回饋回答同樣的 12 道題。

練習本課