Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

돌맹이

[Phython] Pythonic: 파이썬 문법 본문

programming/Python

[Phython] Pythonic: 파이썬 문법

오택 2022. 12. 26. 16:55

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반복문을 매우 간략하게 할 수 있다.