Python Comprehensions
List Comprehensions 는 다른 리스트로부터 리스트를 생성할 수 있게 해주는 특별한 구문이며, 숫자 및 한두 단계의 중첩된 for 루프를 다룰 때 매우 유용합니다.
Python 3 튜토리얼에서 발췌
List comprehensions provide a concise way to create lists. [...] or to create a subsequence of those elements that satisfy a certain condition.
더 심층적인 소개를 원하시면 Python Comprehensions: A step by step Introduction를 읽어보세요.
List comprehension
기존 컬렉션으로부터 For Loop 를 사용하여 새 리스트를 생성하는 방법은 다음과 같습니다.
# Traditional approach: create list using a for loop
names = ['Charles', 'Susan', 'Patrick', 'George']
new_list = []
for n in names:
new_list.append(n)
new_list
['Charles', 'Susan', 'Patrick', 'George']
List Comprehension 으로 동일한 작업을 수행하는 방법은 다음과 같습니다.
# List comprehension: concise way to create a new list
# Syntax: [expression for item in iterable]
names = ['Charles', 'Susan', 'Patrick', 'George']
new_list = [n for n in names] # Create list with all names
new_list
['Charles', 'Susan', 'Patrick', 'George']
로그인하여 이 퀴즈에 답하고 학습 진행 상황을 추적하세요
[expression for item in iterable](expression for item in iterable){expression for item in iterable}expression for item in iterable숫자로도 동일한 작업을 수행할 수 있습니다.
# Nested list comprehension: create tuples from two ranges
# Equivalent to nested for loops
n = [(a, b) for a in range(1, 3) for b in range(1, 3)]
n
[(1, 1), (1, 2), (2, 1), (2, 2)]
Adding conditionals
new_list에 'C’로 시작하는 이름만 포함하고 싶을 때, for 루프를 사용한다면 다음과 같이 할 것입니다.
# Traditional approach: filter with if condition
names = ['Charles', 'Susan', 'Patrick', 'George', 'Carol']
new_list = []
for n in names:
if n.startswith('C'): # Filter names starting with 'C'
new_list.append(n)
print(new_list)
['Charles', 'Carol']
List Comprehension 에서는 if 문을 끝에 추가합니다.
# List comprehension with condition: filter items
# Syntax: [expression for item in iterable if condition]
new_list = [n for n in names if n.startswith('C')]
print(new_list)
['Charles', 'Carol']
로그인하여 이 퀴즈에 답하고 학습 진행 상황을 추적하세요
if condition go in a list comprehension?for keywordfor clauseList Comprehension 에서 if-else 문을 사용하려면 다음과 같이 합니다.
# List comprehension with if-else: conditional expression
# Syntax: [expression_if_true if condition else expression_if_false for item in iterable]
nums = [1, 2, 3, 4, 5, 6]
new_list = [num*2 if num % 2 == 0 else num for num in nums] # Double even numbers
print(new_list)
[1, 4, 3, 8, 5, 12]
Set and Dict comprehensions
The basics of `list` comprehensions also apply to sets and dictionaries.
Set comprehension
# Set comprehension: create a set using comprehension syntax
# Syntax: {expression for item in iterable}
b = {"abc", "def"}
{s.upper() for s in b} # Convert all strings to uppercase
{"ABC", "DEF"}
Dict comprehension
# Dict comprehension: swap keys and values
# Syntax: {key_expression: value_expression for item in iterable}
c = {'name': 'Pooka', 'age': 5}
{v: k for k, v in c.items()} # Reverse key-value pairs
{'Pooka': 'name', 5: 'age'}
로그인하여 이 퀴즈에 답하고 학습 진행 상황을 추적하세요
[key: value for item in iterable](key: value for item in iterable){key_expression: value_expression for item in iterable}{key, value for item in iterable}List comprehension 은 딕셔너리로부터 생성될 수 있습니다.
# List comprehension from dictionary: create formatted strings
c = {'name': 'Pooka', 'age': 5}
["{}:{}".format(k.upper(), v) for k, v in c.items()] # Format as "KEY:value"
['NAME:Pooka', 'AGE:5']