Kudos
Collect
Twiiter
Facebook
Share
베이스

리스트 컴프리헨션 (List Comprehension)

Last updated over 2 years ago
2 0 0 0

기존 리스트에서 약간의 변형이 필요하거나 필터링이 필요할 때, 리스트 컴프리헨션을 이용해 짧은 코드로 원하는 리스트를 손쉽게 만들 수 있다.

아래는 각 과일에 ‘new_’를 붙인 새로운 리스트를 만들었다.

>>> fruits = ['apple', 'banana', 'melon']
>>> ['new_' + fruit for fruit in fruits]

['new_apple', 'new_banana', 'new_melon']

필터를 적용해서, 조건에 맞는 원소로만 리스트를 만들 수도 있다.

>>> nums = [-1, -2, 5, 8, -5, 20]
>>> new_nums = [num * 2 for num in nums if num > 0]
>>> new_nums

[10, 16, 40]

기본 문법은 아래와 같다.

[<expression> for <variable_name> in <sequence> if <condition>]

위 문법을 풀어쓰면 아래와 같은 의미가 된다.

result = []
for variable_name in sequence:
    if condition:
        result.append(expression)

Reference

Essedrop - Make your file online instantly
 

Responses

Leave a response to @mechurak

Please sign in to comment.
Markdown is also available in comment.