Práce s vestavěnými funkcemi

Psaní efektivního kódu v Pythonu

Logan Thomas

Scientific Software Technical Trainer, Enthought

Standardní knihovna Pythonu

  • Standardní knihovna Python 3.6
    • Součást každé standardní instalace Pythonu
  • Vestavěné typy
    • list, tuple, set, dict a další
  • Vestavěné funkce
    • print(), len(), range(), round(), enumerate(), map(), zip() a další
  • Vestavěné moduly
    • os, sys, itertools, collections, math a další
Psaní efektivního kódu v Pythonu

Vestavěná funkce: range()

Explicitní zápis seznamu čísel

nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Psaní efektivního kódu v Pythonu

Vytvoření stejného seznamu pomocí range()

# range(start,stop)
nums = range(0,11)

nums_list = list(nums)
print(nums_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# range(stop)
nums = range(11)

nums_list = list(nums)
print(nums_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Psaní efektivního kódu v Pythonu

Vestavěná funkce: range()

Použití range() s hodnotou kroku

even_nums = range(2, 11, 2)

even_nums_list = list(even_nums)
print(even_nums_list)
[2, 4, 6, 8, 10]
Psaní efektivního kódu v Pythonu

Vestavěná funkce: enumerate()

Vytvoří indexovaný seznam objektů

letters = ['a', 'b', 'c', 'd' ]

indexed_letters = enumerate(letters)

indexed_letters_list = list(indexed_letters)
print(indexed_letters_list)
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
Psaní efektivního kódu v Pythonu

Vestavěná funkce: enumerate()

Lze zadat počáteční hodnotu

letters = ['a', 'b', 'c', 'd' ]

indexed_letters2 = enumerate(letters, start=5)

indexed_letters2_list = list(indexed_letters2)
print(indexed_letters2_list)
[(5, 'a'), (6, 'b'), (7, 'c'), (8, 'd')]
Psaní efektivního kódu v Pythonu

Vestavěná funkce: map()

Aplikuje funkci na objekt

nums = [1.5, 2.3, 3.4, 4.6, 5.0]

rnd_nums = map(round, nums)

print(list(rnd_nums))
[2, 2, 3, 5, 5]
Psaní efektivního kódu v Pythonu

Vestavěná funkce: map()

map() s lambda (anonymní funkce)

nums = [1, 2, 3, 4, 5]

sqrd_nums = map(lambda x: x ** 2, nums)

print(list(sqrd_nums))
[1, 4, 9, 16, 25]
Psaní efektivního kódu v Pythonu

Začněme pracovat s vestavěnými funkcemi!

Psaní efektivního kódu v Pythonu

Preparing Video For Download...