728x90

list comprehension에서 if else를 쓰고 싶다면

res = [x if x >3 else 2 for x in iter_]

즉 for 뒤에 optional if condition이 아니라 실제 값을 받는 부분에 if else ternary operator를 쓰자.

 

 

 

참고자료:

medium.com/techtofreedom/8-levels-of-using-list-comprehension-in-python-efc3c339a1f0

 

8 Levels of Using List Comprehension in Python

A Complete Guidance From Elementary to Profound

medium.com

 

728x90

+ Recent posts