- List comprehensions are clearer than the map and filter built-in functions because they don't require extra lambda expressions.
Effective Python
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> squres = [x ** 2 for x in a]
>>> squres
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> squres_map = map(lambda x: x ** 2, a)
>>> list(squres_map)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
map requies creating a lambda function for the computation, which is visually noisy.
>>> even_squares = [x ** 2 for x in a if x % 2 == 0]
>>> even_squares
[4, 16, 36, 64, 100]
>>> even_squares_fp = map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, a))
>>> list(even_squares_fp)
[4, 16, 36, 64, 100]
Dicts and sets comprehensions
>>> chile_ranks = dict(ghost=1, habanero=2, cayenne=3)
>>> rank_dict = {rank:name for name, rank in chile_ranks.items()}
>>> rank_dict
{1: 'ghost', 2: 'habanero', 3: 'cayenne'}
>>> chile_len_set = {len(name) for name in rank_dict.values()}
>>> chile_len_set
{8, 5, 7}
Recommended Posts