Scrierea buclelor mai eficiente

Scriere eficientă a codului Python

Logan Thomas

Scientific Software Technical Trainer, Enthought

Precizare despre lecție

  • Unele dintre buclele de mai jos pot fi eliminate cu tehnicile din lecțiile anterioare.

  • Exemplele din această lecție sunt folosite în scop demonstrativ.

alt="Semn de avertizare cu textul Atenție: doar în scop demonstrativ"

Scriere eficientă a codului Python

Scrierea buclelor mai eficiente

  • Înțelegeți ce se realizează la fiecare iterație a buclei
  • Mutați calculele unice în afara buclei (înainte)
  • Utilizați conversii globale în afara buclei (după)
  • Orice operație efectuată o singură dată trebuie să fie în afara buclei
Scriere eficientă a codului Python

Mutarea calculelor înainte de buclă

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!
Scriere eficientă a codului Python
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!
Scriere eficientă a codului Python

Mutarea calculelor înainte de buclă

%%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)
Scriere eficientă a codului Python

Mutarea calculelor înainte de buclă

%%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)
Scriere eficientă a codului Python

Utilizarea conversiilor globale

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], ...]
Scriere eficientă a codului Python

Utilizarea conversiilor globale

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], ...]
Scriere eficientă a codului Python
%%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)
Scriere eficientă a codului Python

Timp pentru exerciții!

Scriere eficientă a codului Python

Preparing Video For Download...