list comprehension

hyyyynjn·2021년 8월 18일
0

python 정리

목록 보기
14/26
post-thumbnail
post-custom-banner

List Comprehension의 기본 구조

[for 원소 in 리스트 if]

✅for문을 활용한 list comprehension

📢예시

>>> [i for i in range(5)]
[0, 1, 2, 3, 4]

>>> [i+5 for i in range(5)]
[5, 6, 7, 8, 9]

>>> [i*2 for i in range(5)]
[0, 2, 4, 6, 8]

✅단일 if 문을 포함한 List Comprehension

📌형식

📢예시

>>> [i for i in range(5) if i % 2 == 0]
[0, 2, 4]

>>> [i for i in range(5) if i % 2 == 1]
[1, 3]

evens = [n for n in range(1,21) if n%2 == 0]
print(evens)
# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

✅if와 else문을 포함한 List Comprehension

📢예시

>>> [i if i % 2 == 0 else None for i in range(5) ]
[0, None, 2, None, 4]

arr = [22, 13, 45, 50, 98, 69, 43, 44, 1]
print([x+1 if x >= 45 else x+5 for x in arr])
# [27, 18, 46, 51, 99, 70, 48, 49, 6]

✅중첩 for문을 포함한 List Comprehension

📌형식

📢예시

>>> [i*j for i in range(1,6) for j in range(7,10)]
[7, 8, 9, 14, 16, 18, 21, 24, 27, 28, 32, 36, 35, 40, 45]

multiplications = [i*n for i in range(1,4) for n in range(1,11)]
print(multiplications)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
post-custom-banner

0개의 댓글