Bessere Schleifen schreiben

Effizienten Python-Code schreiben

Logan Thomas

Scientific Software Technical Trainer, Enthought

Hinweis zur Lektion

  • Einige der folgenden Schleifen kannst du mit den Techniken aus den vorherigen Lektionen vermeiden.

  • Die Beispiele in dieser Lektion dienen nur zur Veranschaulichung.

alt=”Warning sign with text Warning: for demonstration purposes only”

Effizienten Python-Code schreiben

Bessere Schleifen schreiben

  • Verstehe, was bei jeder Schleifeniteration passiert.
  • Verschiebe einmalige Berechnungen außerhalb der Schleife.
  • Führe umfangreiche Konvertierungen außerhalb der Schleife durch.
  • Alles, was nur einmal gemacht wird, sollte außerhalb der Schleife sein.
Effizienten Python-Code schreiben

Berechnungen außerhalb einer Schleife verschieben

import numpy as np

names = ['Absol', 'Aron', 'Jynx', 'Natu', 'Onix']
attacks = np.array([130, 70, 50, 50, 45])

for pokemon,attack in zip(names, attacks):
total_attack_avg = attacks.mean()
if attack > total_attack_avg: print( "{}'s attack: {} > average: {}!" .format(pokemon, attack, total_attack_avg) )
Absol's attack: 130 > average: 69.0!
Aron's attack: 70 > average: 69.0!
Effizienten Python-Code schreiben
import numpy as np

names = ['Absol', 'Aron', 'Jynx', 'Natu', 'Onix']
attacks = np.array([130, 70, 50, 50, 45])

# Calculate total average once (outside the loop) total_attack_avg = attacks.mean()
for pokemon,attack in zip(names, attacks): if attack > total_attack_avg: print( "{}'s attack: {} > average: {}!" .format(pokemon, attack, total_attack_avg) )
Absol's attack: 130 > average: 69.0!
Aron's attack: 70 > average: 69.0!
Effizienten Python-Code schreiben

Berechnungen außerhalb einer Schleife verschieben

%%timeit
for pokemon,attack in zip(names, attacks):

    total_attack_avg = attacks.mean()

    if attack > total_attack_avg:
        print(
            "{}'s attack: {} > average: {}!"
            .format(pokemon, attack, total_attack_avg)
        )
74.9 µs ± 3.42 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Effizienten Python-Code schreiben

Berechnungen außerhalb einer Schleife verschieben

%%timeit
# Calculate total average once (outside the loop)
total_attack_avg = attacks.mean()

for pokemon,attack in zip(names, attacks):

    if attack > total_attack_avg:
        print(
            "{}'s attack: {} > average: {}!"
            .format(pokemon, attack, total_attack_avg)
        )
37.5 µs ± 281 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Effizienten Python-Code schreiben

Umfangreiche Konvertierungen nutzen

names = ['Pikachu', 'Squirtle', 'Articuno', ...]
legend_status = [False, False, True, ...]
generations = [1, 1, 1, ...]

poke_data = [] for poke_tuple in zip(names, legend_status, generations):
poke_list = list(poke_tuple)
poke_data.append(poke_list)
print(poke_data)
[['Pikachu', False, 1], ['Squirtle', False, 1], ['Articuno', True, 1], ...]
Effizienten Python-Code schreiben

Umfangreiche Konvertierungen nutzen

names = ['Pikachu', 'Squirtle', 'Articuno', ...]
legend_status = [False, False, True, ...]
generations = [1, 1, 1, ...]

poke_data_tuples = [] for poke_tuple in zip(names, legend_status, generations): poke_data_tuples.append(poke_tuple)
poke_data = [*map(list, poke_data_tuples)]
print(poke_data)
[['Pikachu', False, 1], ['Squirtle', False, 1], ['Articuno', True, 1], ...]
Effizienten Python-Code schreiben
%%timeit
poke_data = []
for poke_tuple in zip(names, legend_status, generations):
    poke_list = list(poke_tuple)
    poke_data.append(poke_list)
261 µs ± 23.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%%timeit
poke_data_tuples = []
for poke_tuple in zip(names, legend_status, generations):
    poke_data_tuples.append(poke_tuple)

poke_data = [*map(list, poke_data_tuples)]
224 µs ± 1.67 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Effizienten Python-Code schreiben

Zeit ein wenig zu üben!

Effizienten Python-Code schreiben

Preparing Video For Download...