본문 바로가기
Programming/python

간결한 python 문법을 쓰자 - one line condition

by 단창 2022. 4. 12.

python 스러운 코드를 짜자 

ex. 
dG ={}
current_node = 1
default_p = 0.1

p = dG.get('p_val', default_p) if current_node in dG else default_p  

#이 한줄코드를 길게 짜면 

if current_node in dG:
    if 'p_val' not in dG[current_node]:
        p = default_p
    else:
        p = dG[current_node]['pval']
else:
    p = default_p
 
코드가 짧아지면 좋지만 그건 가독성 & 명료성을 높이는 방향으로 짧아져야 한다. 
 
dictionary 의 get(key, default_value) 
one-line if condition은 가독성도 높이고 간결성도 높인다. 

 

반응형

'Programming > python' 카테고리의 다른 글

python SSLerror  (0) 2023.10.27
간결한 python 문법을 쓰자 - lambda  (0) 2022.05.09
[vscode] 외부 모듈을 debug하고 싶을때  (0) 2021.11.23
[python] dataframe 의 column 순서변경  (0) 2020.02.13
python 주석  (0) 2020.01.17