본문으로 바로가기

comprehension expression 이란?

Comprehension 은 시퀀스 자료형을 만드는 문법입니다.

 

리스트 생성

>>> nums = [i for i in range(0, 10)]
>>> nums
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 

if 를 사용할 때는 다음과 같습니다. 

>>> nums = [i for i in range(0, 10) if i % 2 == 0]
>>> nums
[0, 2, 4, 6, 8]
>>> nums = [i for i in range(0, 10) if i % 2 == 0 if i % 3 == 0]
>>> nums
[0, 6]

 

모든 조합 구하기.

import random
import pprint

A_dice = ['a1','a2','a3','a4','a5','a6']
B_dice = ['b1','b2','b3','b4','b5','b6']
case = [(x,y) for x in A_dice for y in B_dice]
pprint.pprint(case)
더보기
[('a1', 'b1'),
 ('a1', 'b2'),
 ('a1', 'b3'),
 ('a1', 'b4'),
 ('a1', 'b5'),
 ('a1', 'b6'),
 ('a2', 'b1'),
 ('a2', 'b2'),
 ('a2', 'b3'),
 ('a2', 'b4'),
 ('a2', 'b5'),
 ('a2', 'b6'),
 ('a3', 'b1'),
 ('a3', 'b2'),
 ('a3', 'b3'),
 ('a3', 'b4'),
 ('a3', 'b5'),
 ('a3', 'b6'),
 ('a4', 'b1'),
 ('a4', 'b2'),
 ('a4', 'b3'),
 ('a4', 'b4'),
 ('a4', 'b5'),
 ('a4', 'b6'),
 ('a5', 'b1'),
 ('a5', 'b2'),
 ('a5', 'b3'),
 ('a5', 'b4'),
 ('a5', 'b5'),
 ('a5', 'b6'),
 ('a6', 'b1'),
 ('a6', 'b2'),
 ('a6', 'b3'),
 ('a6', 'b4'),
 ('a6', 'b5'),
 ('a6', 'b6')]

 

딕셔너리 생성

딕셔너리 생성을 컴프리헨션으로 표현할 경우 {} 로 묶습니다.

다음 예제 코드는 color 사용 횟수 나타내는 딕셔너리 자료형을 0으로 초기화했습니다.

colors = ['red', 'yellow', 'green', 'blue', 'black', 'pink']
used_color = {color: 0 for color in colors}
print(used_color)
더보기
{'red': 0, 'yellow': 0, 'green': 0, 'blue': 0, 'black': 0, 'pink': 0}

 

다음과 같이 사용할 경우 typeset 입니다.

>>> what_is = {i for i in range(10)}
>>> type(what_is)
<class 'set'>

 

응용 - 딕셔너리 Key, Value 바꾸기

dic = {
    '1': 'a',
    '2': 'b',
    '3': 'c'
}
print(dic)

r_dic = {value: key for key, value in dic.items()}
print(r_dic)
결과
{'1': 'a', '2': 'b', '3': 'c'}
{'a': '1', 'b': '2', 'c': '3'}