高效結合、計數與迭代

撰寫高效的 Python 程式碼

Logan Thomas

Scientific Software Technical Trainer, Enthought

Pokémon 概覽

  • 訓練家(收集 Pokémon)

alt=「小智:Nintendo 遊戲 Pokémon 中眾多角色(稱為訓練家)之一」

撰寫高效的 Python 程式碼

Pokémon 概覽

  • Pokémon(虛構生物角色)

alt=「傑尼龜、皮卡丘、妙蛙種子、小火龍:Nintendo 遊戲中眾多 Pokémon 的一部分」

撰寫高效的 Python 程式碼

Pokémon 概覽

  • Pokédex(儲存捕捉到的 Pokémon)

alt=「Pokédex:訓練家用來儲存已捕獲 Pokémon 的工具」

撰寫高效的 Python 程式碼

Pokémon 說明

alt=「名為傑尼龜的 Pokémon 與其對應的中繼資料」

撰寫高效的 Python 程式碼

Pokémon 說明

alt=「名為傑尼龜的 Pokémon 與其中繼資料,並標示 Name 與 Generation 欄位」

撰寫高效的 Python 程式碼

Pokémon 說明

alt=「名為傑尼龜的 Pokémon 與其中繼資料,並標示 Type 與 Legendary 欄位」

撰寫高效的 Python 程式碼

Pokémon 說明

alt=「名為傑尼龜的 Pokémon 與其中繼資料,並標示 Health Points、Attack、Defense、Special Attack、Special Defense、Speed、Total 欄位」

撰寫高效的 Python 程式碼

結合物件

names = ['Bulbasaur', 'Charmander', 'Squirtle']
hps = [45, 39, 44]
combined = []

for i,pokemon in enumerate(names):
    combined.append((pokemon, hps[i]))

print(combined)
[('Bulbasaur', 45), ('Charmander', 39), ('Squirtle', 44)]
撰寫高效的 Python 程式碼

用 zip 結合物件

names = ['Bulbasaur', 'Charmander', 'Squirtle']
hps = [45, 39, 44]
combined_zip = zip(names, hps)

print(type(combined_zip))
<class 'zip'>
combined_zip_list = [*combined_zip]

print(combined_zip_list)
[('Bulbasaur', 45), ('Charmander', 39), ('Squirtle', 44)]
撰寫高效的 Python 程式碼

collections 模組

  • Python 標準函式庫的一部分(內建模組)
  • 專用的容器資料型別
    • 通用 dictlistsettuple 的替代方案
  • 常見:
    • namedtuple:具命名欄位的 tuple 子類
    • deque:類 list 容器,追加與彈出很快
    • Counter:用於計數可雜湊物件的 dict
    • OrderedDict:保留項目順序的 dict
    • defaultdict:遺漏值由工廠函式產生的 dict
撰寫高效的 Python 程式碼

collections 模組

  • Python 標準函式庫的一部分(內建模組)
  • 專用的容器資料型別
    • 通用 dictlistsettuple 的替代方案
  • 常見:
    • namedtuple:具命名欄位的 tuple 子類
    • deque:類 list 容器,追加與彈出很快
    • Counter:用於計數可雜湊物件的 dict
    • OrderedDict:保留項目順序的 dict
    • defaultdict:遺漏值由工廠函式產生的 dict
撰寫高效的 Python 程式碼

用迴圈計數

# 每隻 Pokémon 的屬性(共 720)
poke_types = ['Grass', 'Dark', 'Fire', 'Fire', ...]

type_counts = {}
for poke_type in poke_types: if poke_type not in type_counts: type_counts[poke_type] = 1 else: type_counts[poke_type] += 1
print(type_counts)
{'Rock': 41, 'Dragon': 25, 'Ghost': 20, 'Ice': 23, 'Poison': 28, 'Grass': 64,
 'Flying': 2, 'Electric': 40, 'Fairy': 17, 'Steel': 21, 'Psychic': 46, 'Bug': 65,
 'Dark': 28, 'Fighting': 25, 'Ground': 30, 'Fire': 48,'Normal': 92, 'Water': 105}
撰寫高效的 Python 程式碼

collections.Counter()

# 每隻 Pokémon 的屬性(共 720)
poke_types = ['Grass', 'Dark', 'Fire', 'Fire', ...]

from collections import Counter
type_counts = Counter(poke_types)
print(type_counts)
Counter({'Water': 105, 'Normal': 92, 'Bug': 65, 'Grass': 64, 'Fire': 48,
         'Psychic': 46, 'Rock': 41, 'Electric': 40, 'Ground': 30,
         'Poison': 28, 'Dark': 28, 'Dragon': 25, 'Fighting': 25, 'Ice': 23,
         'Steel': 21, 'Ghost': 20, 'Fairy': 17, 'Flying': 2})
撰寫高效的 Python 程式碼

itertools 模組

  • Python 標準函式庫的一部分(內建模組)
  • 產生與使用疊代器的函式式工具
  • 常見:
    • 無窮疊代器:countcyclerepeat
    • 有限疊代器:accumulatechainzip_longest
    • 組合產生器:productpermutationscombinations
撰寫高效的 Python 程式碼

itertools 模組

  • Python 標準函式庫的一部分(內建模組)
  • 產生與使用疊代器的函式式工具
  • 常見:
    • 無窮疊代器:countcyclerepeat
    • 有限疊代器:accumulatechainzip_longest
    • 組合產生器:productpermutationscombinations
撰寫高效的 Python 程式碼

用迴圈取組合

poke_types = ['Bug', 'Fire', 'Ghost', 'Grass', 'Water']

combos = [] for x in poke_types: for y in poke_types: if x == y: continue if ((x,y) not in combos) & ((y,x) not in combos): combos.append((x,y))
print(combos)
[('Bug', 'Fire'), ('Bug', 'Ghost'), ('Bug', 'Grass'), ('Bug', 'Water'),
 ('Fire', 'Ghost'), ('Fire', 'Grass'), ('Fire', 'Water'),
 ('Ghost', 'Grass'), ('Ghost', 'Water'), ('Grass', 'Water')]
撰寫高效的 Python 程式碼

itertools.combinations()

poke_types = ['Bug', 'Fire', 'Ghost', 'Grass', 'Water']

from itertools import combinations
combos_obj = combinations(poke_types, 2)
print(type(combos_obj))
<class 'itertools.combinations'>
combos = [*combos_obj]
print(combos)
[('Bug', 'Fire'), ('Bug', 'Ghost'), ('Bug', 'Grass'), ('Bug', 'Water'),
 ('Fire', 'Ghost'), ('Fire', 'Grass'), ('Fire', 'Water'),
 ('Ghost', 'Grass'), ('Ghost', 'Water'), ('Grass', 'Water')]
撰寫高效的 Python 程式碼

一起來練習吧!

撰寫高效的 Python 程式碼

Preparing Video For Download...