효율적인 결합, 계산 및 반복

효율적인 Python 코드 작성

Logan Thomas

Scientific Software Technical Trainer, Enthought

포켓몬 개요

  • 트레이너 (포켓몬을 수집)

alt="포켓몬 게임의 주인공 Ash Ketchum"

효율적인 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: 해시 가능한 객체를 세는 딕셔너리
    • OrderedDict: 삽입 순서를 유지하는 딕셔너리
    • defaultdict: 누락된 값을 팩토리 함수로 공급하는 딕셔너리
효율적인 Python 코드 작성

collections 모듈

  • Python 표준 라이브러리 내장 모듈
  • 특수 목적 컨테이너 자료형
    • dict, list, set, tuple의 대안
  • 주요 클래스:
    • namedtuple: 필드명이 있는 튜플 서브클래스
    • deque: 빠른 추가·삭제가 가능한 리스트형 컨테이너
    • Counter: 해시 가능한 객체를 세는 딕셔너리
    • OrderedDict: 삽입 순서를 유지하는 딕셔너리
    • defaultdict: 누락된 값을 팩토리 함수로 공급하는 딕셔너리
효율적인 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 표준 라이브러리 내장 모듈
  • 이터레이터 생성·활용을 위한 함수형 도구
  • 주요 기능:
    • 무한 이터레이터: count, cycle, repeat
    • 유한 이터레이터: accumulate, chain, zip_longest
    • 조합 생성기: product, permutations, combinations
효율적인 Python 코드 작성

itertools 모듈

  • Python 표준 라이브러리 내장 모듈
  • 이터레이터 생성·활용을 위한 함수형 도구
  • 주요 기능:
    • 무한 이터레이터: count, cycle, repeat
    • 유한 이터레이터: accumulate, chain, zip_longest
    • 조합 생성기: product, permutations, combinations
효율적인 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...