Kodewick
開始學 →
基礎←→0 / 112

每種寵物幾隻

#061基礎counts[pet] += 1約 4 分鐘

小區登記寵物,記下一串種類,比如 ["cat", "dog", "cat"]。寫 count_pets(pets),回傳一個字典:每種寵物有幾隻,按第一次出現的順序。列表是空的就返回 {}。

示例
count_pets(["cat", "dog", "cat"])→{'cat': 2, 'dog': 1}
count_pets(["fish", "fish", "fish"])→{'fish': 3}
main.py
def count_pets(pets):
    counts = {}
    for pet in pets:
        # 在這裡寫:第一次見到記 1,見過就加 1
        pass
    return counts
Ctrl + Enter 也能執行
結果

寫好了先點「執行」試試示例,沒問題再點「提交」。