Python/Python Programming

[Python] Assigning variables or list as single-line if statements (한줄if문)

Pydole 2018. 5. 7. 20:58

 

한줄 if문으로 변수나 리스트 할당 조건식의 참과 거짓을 변수를 대입하거나 리스트를 생성할 수 있다.

 

 

 

1. 문자열 대입

 

a = 'python'
b = 'This is True' if a == 'python' else 'This is False'
print(b)

---------------------------------------------------------

This is True

 

 

2. 숫자

 

a = 'python'
b = 1 if a == 'python' else 0
print(b)

--------------------------------

1

 

 

3. 리스트

 

a = 'python'
b = [ a for a in a ] if a == 'python' else 0
print(b)

----------------------------------------------

['p', 'y', 't', 'h', 'o', 'n']