Geavanceerde comprehensions

Python-gereedschapskist

Hugo Bowne-Anderson

Data Scientist at DataCamp

Voorwaarden in comprehensions

  • Voorwaarden op de iterable
    [num ** 2 for num in range(10) if num % 2 == 0]
    
[0, 4, 16, 36, 64]
  • Python-documentatie over de %-operator: de % (modulo) operator geeft de rest bij deling van het eerste argument door het tweede.
5 % 2
1
6 % 2
0
Python-gereedschapskist

Voorwaarden in comprehensions

  • Voorwaarden op de uitvoerexpressie
[num ** 2 if num % 2 == 0 else 0 for num in range(10)]
[0, 0, 4, 0, 16, 0, 36, 0, 64, 0]
Python-gereedschapskist

Dict-comprehensions

  • Maak dictionaries
  • Gebruik accolades {} in plaats van brackets []
pos_neg = {num: -num for num in range(9)}

print(pos_neg)
{0: 0, 1: -1, 2: -2, 3: -3, 4: -4, 5: -5, 6: -6, 7: -7, 8: -8}
print(type(pos_neg))
<class 'dict'>
Python-gereedschapskist

Laten we oefenen!

Python-gereedschapskist

Preparing Video For Download...