라일락 꽃이 피는 날

[Python] Comprehension (함축) 본문

프로그래밍/Python

[Python] Comprehension (함축)

eunki 2021. 6. 14. 14:59
728x90

Comprehension (함축)

 

1. List Comprehension

a = [x for x in range(101)]
    
print(a)  # [0, 1, 2, ..., 99, 100]
b = [x for x in range(101) if x % 2 == 0]

print(b)  # [0, 2, 4, ..., 98, 100]
from random import randint

c = [randint(0, 100) for x in range(101)]

print(c)  # [55, 17, 6, ..., 23, 91] 랜덤 값
d = [True if x % 2 == 0 else False for x in range(101)]

print(d)  # [True, False, True, ..., False, True]
e = [
    ('아메리카노', 3000),
    ('에스프레소', 2500),
    ('카페모카', 3500),
    ('카페라떼', 4000),
    ('레몬티', 5000)
]
f = [(menu, price) for menu, price in e if price >= 3500]
g = [(menu, price) if price >= 3500 else (menu, '싸다') for menu, price in e]

print(e)  # [('아메리카노', 3000), ('에스프레소', 2500), ('카페모카', 3500), ('카페라떼', 4000), ('레몬티', 5000)]
print(f)  # [('카페모카', 3500), ('카페라떼', 4000), ('레몬티', 5000)]
print(g)  # [('아메리카노', '싸다'), ('에스프레소', '싸다'), ('카페모카', 3500), ('카페라떼', 4000), ('레몬티', 5000)]

 

 

 

2. Dict Comprehension

h = {str(x): x for x in range(10)}

print(h)  # {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
728x90

'프로그래밍 > Python' 카테고리의 다른 글

[Python] fileopen  (0) 2021.06.15
[Python] strftime, strptime  (0) 2021.06.14
[Python] Packing, Unpacking  (0) 2021.06.14
[Python] 람다 함수 (lambda function)  (0) 2021.06.04
[Python] Scope (스코프)  (0) 2021.06.04