オブジェクトの結合・カウント・反復処理

効率的なPythonコードの書き方

Logan Thomas

Scientific Software Technical Trainer, Enthought

ポケモン概要

  • トレーナー(ポケモンを収集する)

alt="ポケモンゲームに登場するトレーナーの一人、サトシ"

効率的なPythonコードの書き方

ポケモン概要

  • ポケモン(架空の動物キャラクター)

alt="Squirtle、Pikachu、Bulbasaur、Charmander;ポケモンゲームに登場するポケモンの一部"

効率的なPythonコードの書き方

ポケモン概要

  • ポケモン図鑑(捕まえたポケモンを保存する)

alt="トレーナーが捕まえたポケモンを保存するツール、ポケモン図鑑"

効率的なPythonコードの書き方

ポケモンの説明

alt="ポケモンのSquirtleとそのメタデータ"

効率的なPythonコードの書き方

ポケモンの説明

alt="ポケモンのSquirtleとそのメタデータ、NameフィールドとGenerationフィールドが強調表示されている"

効率的なPythonコードの書き方

ポケモンの説明

alt="ポケモンのSquirtleとそのメタデータ、TypeフィールドとLegendaryフィールドが強調表示されている"

効率的なPythonコードの書き方

ポケモンの説明

alt="ポケモンのSquirtleとそのメタデータ、HP・攻撃・防御・特攻・特防・素早さ・合計フィールドが強調表示されている"

効率的な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標準ライブラリに含まれる(組み込みモジュール)
  • 特化したコンテナデータ型
    • dict、list、set、tupleの代替
  • 主なもの:
    • namedtuple: 名前付きフィールドを持つタプルサブクラス
    • deque: 高速な追加・削除が可能なリスト型コンテナ
    • Counter: ハッシュ可能なオブジェクトをカウントするdict
    • OrderedDict: 挿入順を保持するdict
    • defaultdict: 欠損値をファクトリ関数で補完するdict
効率的なPythonコードの書き方

collectionsモジュール

  • Python標準ライブラリに含まれる(組み込みモジュール)
  • 特化したコンテナデータ型
    • dict、list、set、tupleの代替
  • 主なもの:
    • namedtuple: 名前付きフィールドを持つタプルサブクラス
    • deque: 高速な追加・削除が可能なリスト型コンテナ
    • Counter: ハッシュ可能なオブジェクトをカウントするdict
    • OrderedDict: 挿入順を保持するdict
    • defaultdict: 欠損値をファクトリ関数で補完するdict
効率的なPythonコードの書き方

ループによるカウント

# Each Pokémon's type (720 total)
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()

# Each Pokémon's type (720 total)
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...