Efficiënt combineren, tellen en itereren

Efficiënte Python-code schrijven

Logan Thomas

Scientific Software Technical Trainer, Enthought

Overzicht van Pokémon

  • Trainers (verzamelen Pokémon)

alt=”Ash Ketchum; een van de vele personages (trainers) in de Nintendo-game Pokémon”

Efficiënte Python-code schrijven

Overzicht van Pokémon

  • Pokémon (fictieve dieren)

alt=”Squirtle, Pikachu, Bulbasaur en Charmander; enkele van de vele Pokémon in de Nintendo-game”

Efficiënte Python-code schrijven

Overzicht van Pokémon

  • Pokédex (slaat gevangen Pokémon op)

alt=”Pokédex, een tool waarmee trainers gevangen Pokémon opslaan”

Efficiënte Python-code schrijven

Beschrijving van Pokémon

alt=”De Pokémon Squirtle met bijbehorende metadata”

Efficiënte Python-code schrijven

Beschrijving van Pokémon

alt=”De Pokémon Squirtle met metadata; velden Name en Generation gemarkeerd”

Efficiënte Python-code schrijven

Beschrijving van Pokémon

alt=”De Pokémon Squirtle met metadata; velden Type en Legendary gemarkeerd”

Efficiënte Python-code schrijven

Beschrijving van Pokémon

alt=”De Pokémon Squirtle met metadata; velden HP, Attack, Defense, Sp. Atk, Sp. Def, Speed en Total gemarkeerd”

Efficiënte Python-code schrijven

Objecten combineren

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)]
Efficiënte Python-code schrijven

Combineren met 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)]
Efficiënte Python-code schrijven

De collections-module

  • Onderdeel van de Python-standaardbibliotheek (ingebouwd)
  • Gespecialiseerde container-datatypes
    • Alternatieven voor algemene dict, list, set en tuple
  • Opvallend:
    • namedtuple: tuple-subklassen met benoemde velden
    • deque: lijstachtige container met snelle appends en pops
    • Counter: dict voor het tellen van hashable objecten
    • OrderedDict: dict die invoegvolgorde bewaart
    • defaultdict: dict die een factoryfunctie aanroept voor ontbrekende waarden
Efficiënte Python-code schrijven

De collections-module

  • Onderdeel van de Python-standaardbibliotheek (ingebouwd)
  • Gespecialiseerde container-datatypes
    • Alternatieven voor algemene dict, list, set en tuple
  • Opvallend:
    • namedtuple: tuple-subklassen met benoemde velden
    • deque: lijstachtige container met snelle appends en pops
    • Counter: dict voor het tellen van hashable objecten
    • OrderedDict: dict die invoegvolgorde bewaart
    • defaultdict: dict die een factoryfunctie aanroept voor ontbrekende waarden
Efficiënte Python-code schrijven

Tellen met een lus

# Het type van elke Pokémon (totaal 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}
Efficiënte Python-code schrijven

collections.Counter()

# Het type van elke Pokémon (totaal 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})
Efficiënte Python-code schrijven

De itertools-module

  • Onderdeel van de Python-standaardbibliotheek (ingebouwd)
  • Functionele tools voor het maken en gebruiken van iterators
  • Opvallend:
    • Oneindige iterators: count, cycle, repeat
    • Eindige iterators: accumulate, chain, zip_longest, enz.
    • Combinatiegenerators: product, permutations, combinations
Efficiënte Python-code schrijven

De itertools-module

  • Onderdeel van de Python-standaardbibliotheek (ingebouwd)
  • Functionele tools voor het maken en gebruiken van iterators
  • Opvallend:
    • Oneindige iterators: count, cycle, repeat
    • Eindige iterators: accumulate, chain, zip_longest, enz.
    • Combinatiegenerators: product, permutations, combinations
Efficiënte Python-code schrijven

Combinaties met een lus

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')]
Efficiënte Python-code schrijven

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')]
Efficiënte Python-code schrijven

Laten we oefenen!

Efficiënte Python-code schrijven

Preparing Video For Download...