Python - List / Dictionary comprehension

Enjoywater·2020년 8월 24일
0

TIL

목록 보기
9/33
post-thumbnail

List Comprehension

list comprehension이란?

새로운 list를 만들 때 사용할 수 있는 간단한 표현식이며,
list와 마찬가지로 대괄호 - [ ] 를 사용하여 작성한다.

형식은 2종류이며 각각 아래와 같이 사용할 수 있다.

  • [ 표현식 for 원소 in 반복가능한 객체 ]
  • [ 표현식 for 원소 in 반복가능한 객체 if문 ]

2가지 형식을 코드를 통해 쉽게 살펴보도록 하자.

조건문이 없는 표현식

result = []

for num in range(1,11):
    result.append(num)

print(result)

# 결과값 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

위 코드는 일반적인 for loop를 이용해서 비어있는 list에 element를 추가하는 방법이다.
이 코드를 list comprehension을 사용해서 작성해보면,

result = [ ele for ele in range(1,11) ]

print(result)

# 결과값 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

간단하게 한 줄로 작성할 수 있다.



조건문이 있는 표현식

result = []

for num in range(1,11):
    if num > 5:
        result.append(num)

print(result)

# 결과값 -> [6, 7, 8, 9, 10]

앞서 보았던 코드에 조건문을 추가하였다.
위 코드를 바꾸어보면

result = [ ele for ele in range(1,11) if ele > 5 ]

print(result)

# 결과값 -> [6, 7, 8, 9, 10]

로 간단하게 출력할 수 있다.


Dictionary Comprehension

Dictionary comprehension은 list comprehension과 큰 차이가 없다.
dictionary의 구조list의 구조와 다르기 때문에 해당 부분만 잘 구분해서 사용하면 된다.

dictionary와 마찬가지로 중괄호 - { } 를 사용하며,
key:value 형태로 표현식이 작성된다.

  • { key:value for 원소 in 반복가능한 객체 }
  • { key:value for 원소 in 반복가능한 객체 if문 }
fruit_color = {"apple" : "red", "banana" : "yellow", "peach":"pink"}
no_bana = {}

for key in fruit_color:
    if key != "banana":
        no_bana[key] = fruit_color[key]

print(no_bana)

# 결과값 -> {'apple': 'red', 'peach': 'pink'}

이 코드를 dictionary comprehension을 사용해서 작성해보면,

fruit_color = {"apple" : "red", "banana" : "yellow", "peach":"pink"}

no_bana = { key:val for key,val in fruit_color.items() if key != "banana" }

print(no_bana)

# 결과값 -> {'apple': 'red', 'peach': 'pink'}

간단하게 한 줄로 작성할 수 있다.




profile
블로그 이전 👉🏻 enjoywater.tistory.com

0개의 댓글