Item 5: Use list comprehension instead of map and filter (p15 ~ 16)
Higher-order functions are functional and cool (?), But they generate lambdas one by one, so it's difficult to read unless you're used to it. Guido seems to dislike higher-order functions in the first place, and there will be a limited number of situations where he will actively use them.
If you can use the inclusion notation, write it in the inclusion notation!
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#Write an expression that squares each sequence
# map()in the case of
squares = map(lambda x: x ** 2, a)
print(list(squares))
>>>
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#In case of inclusion notation
squares = [x ** 2 for x in a]
print(squares)
>>>
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The latter is easier to see, isn't it? Let's add a condition to extract only even numbers.
#Only even numbers are squared and extracted
# map()And filter()If you write in
even_squares = map(lambda x: x**2, filter(lambda x: x % 2 == 0, a))
print(list(even_squares))
>>>
[4, 16, 36, 64, 100]
#In case of inclusion notation
even_squares = [x **2 for x in a if x % 2 == 0]
print(even_squares)
>>>
[4, 16, 36, 64, 100]
This is clearer! There is no room for hesitation
By the way, not only lists but also dictionaries and sets can be used for inclusion notation.
#Invert dictionary keys and values, create new dictionaries
chile_ranks = {'ghost': 1, 'habanero': 2, 'cayenne': 3}
rank_dist = {rank: name for name, rank in chile_ranks.items()}
chile_len_set = {len(name) for name in rank_dist.values()}
print(rank_dist)
print(chile_len_set)
>>>
{1: 'ghost', 2: 'habanero', 3: 'cayenne'}
{8, 5, 7}
Higher-order functions aren't bad, but it's better to write your code for readability. (Except for those who really like functional programming ...)
Recommended Posts