over 3 years ago

Use List Comprehensions Instead of map and filter

list comprehensions 很重要,寫 Python 一定用得到。

使用 list comprehension

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [x**2 for x in a]

使用 map()

squares = map(lambda x: x ** 2, a)

使用 list comprehension

even_squares = [x**2 for x in a if x % 2 == 0]

使用 map() + filter()

alt = map(lambda x: x**2, filter(lambda x: x % 2 == 0, a))

dictionary 和 set 也可以

chile_ranks = {'ghost': 1, 'habanero': 2, 'cayenne': 3}
rank_dict = {rank: name for name, rank in chile_ranks.items()}
chile_len_set = {len(name) for name in rank_dict.values()}

相關

Python 慣用語 - 17 List Comprehensions

← Effective Python 心得筆記: Item 6 Effective Python 心得筆記: Item 8 →
 
comments powered by Disqus