Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

파이썬 공부하기

[Python] 파이썬 List Comprehension 본문

파이썬 기초

[Python] 파이썬 List Comprehension

파이썬러버 2024. 1. 12. 02:59

파이썬 리스트 컴프리헨션은 간결하게 리스트를 생성하기 위한 특별한 문법입니다. 리스트 컴프리헨션을 사용하면 루프를 사용하여 리스트를 생성하는 과정을 한 줄로 축약할 수 있습니다. 이는 코드를 더 간결하게 작성할 수 있게 해주며 가독성을 높여줍니다.

기본 구조

리스트 컴프리헨션은 일반적으로 다음과 같은 구조를 갖습니다:

new_list = [expression for item in iterable if condition]
  • expression: 각 아이템에 대한 계산식 또는 표현식
  • item: 이터러블 객체(리스트, 튜플 등)에서 가져온 각 항목
  • iterable: 이터러블 객체
  • condition (optional): 필터링을 위한 조건

예제

1. 간단한 리스트 생성

numbers = [1, 2, 3, 4, 5]
squared_numbers = [x**2 for x in numbers]
print(squared_numbers)
# 출력: [1, 4, 9, 16, 25]

2. 조건을 추가한 리스트 생성

even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
# 출력: [2, 4]

3. 문자열 리스트에서 길이가 3 이하인 단어만 추출

words = ["apple", "banana", "grape", "kiwi"]
short_words = [word for word in words if len(word) <= 3]
print(short_words)
# 출력: ['kiwi']

4. 이중 리스트 풀기

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)
# 출력: [1, 2, 3, 4, 5, 6, 7, 8, 9]

5. 조건을 포함한 이중 리스트 풀기

even_numbers_flat = [num for row in matrix for num in row if num % 2 == 0]
print(even_numbers_flat)
# 출력: [2, 4, 6, 8]

리스트 컴프리헨션을 사용하면 루프와 조건문을 한 줄로 간결하게 작성할 수 있어 코드의 가독성과 효율성을 높여줍니다.