파이썬에서는 컴프리헨션이라는 구문을 사용할 수 있다.
컴프리헨션 코딩 스타일은 제너레이터를 사용하는 함수로 확장할 수 있다.
제너레이터는 함수가 점진적으로 반환하는 값으로 이뤄지는 스트림을 만들어준다.
이터레이터를 사용할 수 있는 곳이라면 어디에서나 제너레이터 함수를 호출한 결과를 사용할 수 있다.
리스트 컴프리헨션!
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = []
for x in a:
squares.append(x**2)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares = [x**2 for x in a]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
alt = map(lambda x: x ** 2, a)
even_squares = [x**2 for x in a if x % 2 == 0]
print(even_squares)
[4, 16, 36, 64, 100]
alt = map(lambda x : x**2, filter(lambda x: x % 2 == 0, a))
even_squares
[4, 16, 36, 64, 100]
even_squares_dict = {x: x**2 for x in a if x % 2 == 0}
threes_cubed_set = {x**3 for x in a if x % 3 == 0}
print(even_squares_dict)
print(threes_cubed_set)
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100} {216, 729, 27}
alt_dict = dict(map(lambda x: (x, x**2), filter(lambda x: x % 2 == 0, a)))
alt_set = set(map(lambda x: (x, x**3), filter(lambda x: x % 3 == 0, a)))