Terry Very Good

[python] for문을 간결하게 짜는 법 본문

프로그래밍/PYTHON

[python] for문을 간결하게 짜는 법

테리베리 2022. 10. 5. 15:37
728x90
반응형

for문을 간결하게 짜는 법

# for문 기본형
l1 = [1,2,3]
l2 = []
for i in l1:
    l2.append(i**2)
print(l2) 

>> [1,4,9]


# for문 간결하게 쓰기
l1 = [1,2,3]
l2 = [i**2 for i in l1] 
print(l2)

>> [1,4,9]


# for문 간결하게 쓰면서 i가 2일 때는 안쓰기
l1 = [1,2,3]
l2 = [i**2 for i in l1 if i != 2] 
print(l2)

>> [1,9]
728x90
반응형