한 줄에 리스트 작성하기 (List Comprehensions)
Source: Dev.to
위의 링크에 있는 전체 텍스트를 제공해 주시면, 해당 내용을 한국어로 번역해 드리겠습니다. 코드 블록, URL 및 마크다운 형식은 그대로 유지하고, 텍스트만 번역해 드립니다. 부탁드립니다.
소개
파이썬에서 루프를 사용해 리스트를 만들 수 있지만, 리스트 컴프리헨션을 사용하면 같은 작업을 한 줄의 가독성 좋은 코드로 수행할 수 있습니다.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = []
for n in numbers:
squares.append(n * n)
print(squares)
# Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
리스트 컴프리헨션을 사용한 동일한 결과:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [n * n for n in numbers]
print(squares)
# Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
구문
리스트 컴프리헨션을 왼쪽에서 오른쪽으로 문장처럼 읽으세요:
[expression for variable in iterable]
- expression – 새 리스트에 넣고 싶은 값(계산, 함수 호출 등).
- variable – 반복 변수(예:
n). - iterable – 리스트, range, 문자열 등 모든 반복 가능한 객체.
필터 추가
[expression for variable in iterable if condition]
if 절은 condition이 True인 항목만 남깁니다.
예시
간단한 변환
names = ["alex", "priya", "sam", "jordan"]
upper_names = [name.upper() for name in names]
print(upper_names)
# Output: ['ALEX', 'PRIYA', 'SAM', 'JORDAN']
lengths = [len(name) for name in names]
print(lengths)
# Output: [4, 5, 3, 6]
numbers = range(1, 6)
doubled = [n * 2 for n in numbers]
print(doubled)
# Output: [2, 4, 6, 8, 10]
필터링
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [n for n in numbers if n % 2 == 0]
print(evens)
# Output: [2, 4, 6, 8, 10]
scores = [45, 92, 78, 61, 34, 88, 55, 97]
passing = [s for s in scores if s >= 60]
print(passing)
# Output: [92, 78, 61, 88, 97]
변환과 필터링을 함께 사용
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_evens = [n * n for n in numbers if n % 2 == 0]
print(squared_evens)
# Output: [4, 16, 36, 64, 100]
문자열 작업
sentence = "Hello World"
letters = [char for char in sentence if char != " "]
print(letters)
# Output: ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
words = [" hello ", " world ", " python "]
cleaned = [w.strip() for w in words]
print(cleaned)
# Output: ['hello', 'world', 'python']
딕셔너리 컴프리헨션
names = ["Alex", "Priya", "Sam"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)
# Output: {'Alex': 4, 'Priya': 5, 'Sam': 3}
scores = {"Alex": 92, "Priya": 58, "Sam": 75, "Jordan": 44}
passing = {name: score for name, score in scores.items() if score >= 60}
print(passing)
# Output: {'Alex': 92, 'Sam': 75}
컴프리헨션을 사용하면 안 되는 경우
논리가 복잡해지면 일반 루프가 더 명확합니다:
# Hard to read comprehension
result = [process(transform(validate(x))) for x in data if check_one(x) and check_two(x)]
# Clearer as a loop
result = []
for x in data:
if check_one(x) and check_two(x):
validated = validate(x)
transformed = transform(validated)
result.append(process(transformed))
Rule of thumb: 한눈에 이해할 수 있을 때만 컴프리헨션을 사용하세요.
연습 문제
파일 comprehensions_practice.py를 만들고, 컴프리헨션만 사용하여 주어진 데이터를 가지고 다음 작업을 수행하세요:
temperatures_c = [0, 10, 20, 30, 40, 100]
words = ["Python", "is", "great", "for", "AI", "and", "ML"]
students = [
{"name": "Alex", "score": 88},
{"name": "Priya", "score": 52},
{"name": "Sam", "score": 76},
{"name": "Jordan", "score": 91},
{"name": "Lisa", "score": 43}
]
- 각 온도를 화씨로 변환(
F = C * 9/5 + 32)하고 결과를 리스트에 저장합니다. - 길이가 세 글자보다 긴 단어들의 리스트를 만듭니다.
- 학생 이름만 추출한 리스트를 만듭니다.
- 점수가 60점 이상인 학생들의 이름 리스트를 추출합니다.
- 각 학생의 이름을 키로, 점수를 값으로 하는 딕셔너리를 만듭니다.