
List comprehension은 리스트를 생성하는 간단한 방법입니다.
List comprehension에 사용할 수 있는 함수로는 filter(), map(), reduce()가 있습니다.
List comprehension의 장점은 다음과 같습니다.
- 코드가 간결하고 읽기 쉽습니다.
- 리스트를 생성하는 시간이 빠릅니다.
- 여러 리스트를 조합하고 변형하는 데 유용합니다.
예를 들어, 다음과 같이 리스트를 생성할 수 있습니다.
#hostingforum.kr
python
numbers = [1, 2, 3, 4, 5]
double_numbers = [x * 2 for x in numbers]
print(double_numbers) # [2, 4, 6, 8, 10]
filter() 함수를 사용하여 리스트에서 특정 조건을 만족하는 요소를 필터링할 수 있습니다.
#hostingforum.kr
python
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4]
map() 함수를 사용하여 리스트의 요소를 변형할 수 있습니다.
#hostingforum.kr
python
numbers = [1, 2, 3, 4, 5]
double_numbers = list(map(lambda x: x * 2, numbers))
print(double_numbers) # [2, 4, 6, 8, 10]
reduce() 함수를 사용하여 리스트의 요소를 조합할 수 있습니다.
#hostingforum.kr
python
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_numbers) # 15
2025-06-18 16:36