돌맹이
[Phython] Pythonic: 파이썬 문법 본문
o가 들어간 단어만 추출하여 새로운 list를 만들어보자
## 일반 문법을 사용한 반복문
a = ['computer','apple','human','zoo','country']
result_list=[]
for x in a:
if "o" in x:
result_list.append(x)
print(result_list)
['computer', 'zoo', 'country']
## Pythonic을 사용한 반복문
a = ['computer','apple','human','zoo','country']
result_list2 = [x for x in a if 'o' in x]
print(result_list2)
['computer', 'zoo', 'country']
두 코드의 결과값은 같다.
Python에서 제공하는 Pythonic 문법을 이용하면 for loop반복문을 매우 간략하게 할 수 있다.
'programming > Python' 카테고리의 다른 글
[Python] 문자열 포매팅(String Formatting) (0) | 2022.12.27 |
---|---|
[Python] Dictionary 자료형 (0) | 2022.12.27 |
[Python] list와 tuple (0) | 2022.12.26 |
[Python] Github를 이용해 동일한 가상환경 생성하기 (0) | 2022.12.23 |