Menggabung, menghitung, dan meng-iterasi secara efisien

Menulis Kode Python yang Efisien

Logan Thomas

Scientific Software Technical Trainer, Enthought

Gambaran Pokémon

  • Trainer (mengumpulkan Pokémon)

alt=”Ash Ketchum; salah satu dari banyak karakter (disebut trainer) dalam gim Nintendo Pokémon”

Menulis Kode Python yang Efisien

Gambaran Pokémon

  • Pokémon (karakter hewan fiksi)

alt=”Squirtle, Pikachu, Bulbasaur, dan Charmander; beberapa dari banyak Pokémon dalam gim Nintendo”

Menulis Kode Python yang Efisien

Gambaran Pokémon

  • Pokédex (menyimpan Pokémon yang ditangkap)

alt=”Pokédex, alat yang digunakan trainer untuk menyimpan Pokémon yang ditangkap”

Menulis Kode Python yang Efisien

Deskripsi Pokémon

alt=”Pokémon bernama Squirtle beserta metadata-nya”

Menulis Kode Python yang Efisien

Deskripsi Pokémon

alt=”Pokémon bernama Squirtle beserta metadata-nya dengan kolom Name dan Generation disorot”

Menulis Kode Python yang Efisien

Deskripsi Pokémon

alt=”Pokémon bernama Squirtle beserta metadata-nya dengan kolom Type dan Legendary disorot”

Menulis Kode Python yang Efisien

Deskripsi Pokémon

alt=”Pokémon bernama Squirtle beserta metadata-nya dengan kolom Health Points, Attack, Defense, Special Attack, Special Defense, Speed, dan Total disorot”

Menulis Kode Python yang Efisien

Menggabungkan objek

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)]
Menulis Kode Python yang Efisien

Menggabungkan dengan 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)]
Menulis Kode Python yang Efisien

Modul collections

  • Bagian dari Python Standard Library (modul bawaan)
  • Tipe kontainer khusus
    • Alternatif untuk dict, list, set, dan tuple umum
  • Penting:
    • namedtuple: subclass tuple dengan field bernama
    • deque: kontainer mirip list dengan append dan pop cepat
    • Counter: dict untuk menghitung objek hashable
    • OrderedDict: dict yang mempertahankan urutan entri
    • defaultdict: dict yang memanggil fungsi pabrik untuk nilai yang hilang
Menulis Kode Python yang Efisien

Modul collections

  • Bagian dari Python Standard Library (modul bawaan)
  • Tipe kontainer khusus
    • Alternatif untuk dict, list, set, dan tuple umum
  • Penting:
    • namedtuple: subclass tuple dengan field bernama
    • deque: kontainer mirip list dengan append dan pop cepat
    • Counter: dict untuk menghitung objek hashable
    • OrderedDict: dict yang mempertahankan urutan entri
    • defaultdict: dict yang memanggil fungsi pabrik untuk nilai yang hilang
Menulis Kode Python yang Efisien

Menghitung dengan loop

# Tipe tiap Pokémon (total 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}
Menulis Kode Python yang Efisien

collections.Counter()

# Tipe tiap Pokémon (total 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})
Menulis Kode Python yang Efisien

Modul itertools

  • Bagian dari Python Standard Library (modul bawaan)
  • Alat fungsional untuk membuat dan memakai iterator
  • Penting:
    • Iterator tak hingga: count, cycle, repeat
    • Iterator hingga: accumulate, chain, zip_longest, dll.
    • Generator kombinasi: product, permutations, combinations
Menulis Kode Python yang Efisien

Modul itertools

  • Bagian dari Python Standard Library (modul bawaan)
  • Alat fungsional untuk membuat dan memakai iterator
  • Penting:
    • Iterator tak hingga: count, cycle, repeat
    • Iterator hingga: accumulate, chain, zip_longest, dll.
    • Generator kombinasi: product, permutations, combinations
Menulis Kode Python yang Efisien

Kombinasi dengan loop

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')]
Menulis Kode Python yang Efisien

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')]
Menulis Kode Python yang Efisien

Ayo berlatih!

Menulis Kode Python yang Efisien

Preparing Video For Download...