Comprehensions

Python pro uživatele R

Daniel Chen

Instructor

Comprehensions jsou cykly

  • Iterace (průchod) přes seznam
  • Aplikace funkce
  • Uložení výsledků do nového seznamu
Python pro uživatele R

List comprehension

Cyklus
data = [1, 2, 3, 4, 5]
new = []
for x in data:
    new.append(x**2)
print(new)
[1, 4, 9, 16, 25]
Comprehension
data = [1, 2, 3, 4, 5]

new = [x**2 for x in data]
print(new)
[1, 4, 9, 16, 25]
Python pro uživatele R

Dictionary comprehension

Cyklus
data = [1, 2, 3, 4, 5]
new = {}

for x in data:
    new[x] = x**2
print(new)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Comprehension
data = [1, 2, 3, 4, 5]

new = {x: x**2 for x in data}
print(new)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Python pro uživatele R

Alternativy k cyklu `for`

  • Cyklus for pro iteraci
  • R: funkce sapply, lapply, apply
  • Python: funkce map a metoda apply
Python pro uživatele R

Map

Cyklus for
def sq(x):
    return x**2

l = [1, 2, 3]
for i in l:
    print(sq(i))
1
4
9
Map
map(sq, l)
<map at 0x7f41cca38358>
list(map(sq, l))
[1, 4, 9]
Python pro uživatele R

Pojďme si procvičit!

Python pro uživatele R

Preparing Video For Download...