9.7. Comprehension Filter¶
9.7.1. Recap¶
>>> result = []
>>>
>>> for x in range(0,5):
... if x % 2 == 0:
... result.append(x)
>>>
>>> print(result)
[0, 2, 4]
9.7.2. Syntax¶
>>>
... result = [<RETURN> for <VARIABLE> in <ITERABLE> if <CONDITION>]
9.7.3. Example¶
>>> result = [x for x in range(0,5) if x%2==0]
>>>
>>> print(result)
[0, 2, 4]
9.7.4. Filter list[tuple]¶
>>> DATA = [
... ('Sepal length', 'Sepal width', 'Petal length', 'Petal width', 'Species'),
... (5.8, 2.7, 5.1, 1.9, 'virginica'),
... (5.1, 3.5, 1.4, 0.2, 'setosa'),
... (5.7, 2.8, 4.1, 1.3, 'versicolor'),
... (6.3, 2.9, 5.6, 1.8, 'virginica'),
... (6.4, 3.2, 4.5, 1.5, 'versicolor'),
... (4.7, 3.2, 1.3, 0.2, 'setosa'),
... (7.0, 3.2, 4.7, 1.4, 'versicolor')]
>>>
>>>
>>> [row for row in DATA[1:] if row[-1] == 'setosa']
[(5.1, 3.5, 1.4, 0.2, 'setosa'), (4.7, 3.2, 1.3, 0.2, 'setosa')]
>>>
>>> [features for *features,label in DATA[1:] if label == 'setosa']
[[5.1, 3.5, 1.4, 0.2], [4.7, 3.2, 1.3, 0.2]]
>>>
>>> [X for *X,y in DATA[1:] if y == 'setosa']
[[5.1, 3.5, 1.4, 0.2], [4.7, 3.2, 1.3, 0.2]]
9.7.5. Filter list[dict]¶
>>> PEOPLE = [{'is_astronaut': True, 'name': 'Melissa Lewis'},
... {'is_astronaut': True, 'name': 'Mark Watney'},
... {'is_astronaut': False, 'name': 'Rick Martinez'},
... {'is_astronaut': True, 'name': 'Alex Vogel'}]
>>>
>>>
>>> astronauts = []
>>>
>>> for person in PEOPLE:
... if person['is_astronaut']:
... astronauts.append(person['name'])
>>>
>>> print(astronauts)
['Melissa Lewis', 'Mark Watney', 'Alex Vogel']
>>> PEOPLE = [{'is_astronaut': True, 'name': 'Melissa Lewis'},
... {'is_astronaut': True, 'name': 'Mark Watney'},
... {'is_astronaut': False, 'name': 'Rick Martinez'},
... {'is_astronaut': True, 'name': 'Alex Vogel'}]
>>>
>>>
>>> astronauts = [person['name']
... for person in PEOPLE
... if person['is_astronaut']]
>>>
>>> print(astronauts)
['Melissa Lewis', 'Mark Watney', 'Alex Vogel']
9.7.6. Good Practices¶
>>> result = [pow(x, 2) for x in range(0, 5) if x % 2 == 0]
>>> result = [pow(x,2) for x in range(0,5) if x%2==0]
>>> result = [pow(x,2)
... for x in range(0,5)
... if x % 2 == 0]
>>> result = [pow(x,2)
... for x in range(0,5)
... if x % 2 == 0]
9.7.7. Assignments¶
"""
* Assignment: Comprehension Filter Even
* Required: yes
* Complexity: easy
* Lines of code: 2 lines
* Time: 3 min
English:
1. Use list comprehension
2. Generate `result: list[int]`
of even numbers from 5 to 20 (without 20)
3. Run doctests - all must succeed
Polish:
1. Użyj rozwinięcia listowego
2. Wygeneruj `result: list[int]`
parzystych liczb z przedziału 5 do 20 (bez 20)
3. Uruchom doctesty - wszystkie muszą się powieść
Hints:
* `range()`
* `%`
* `==`
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> assert type(result) is list, \
'Result should be a list'
>>> assert all(type(x) is int for x in result), \
'Result should be a list of int'
>>> result
[6, 8, 10, 12, 14, 16, 18]
"""
# Even numbers from 5 to 20 (without 20)
# type: list[int]
result = ...