Python 기초 여섯 번째 시간. 오늘은 list, dictionary의 생성을 간단하게 축약해서 할 수 있는 list comprehension, dictionary comprehension, 그리고 조건을 부여한 conditional comprehension까지 정리를 해보겠다.
이런 comprehension은 아는 사람은 계속 쓰고 모르는 사람은 계속 쓰지 않는 약간의 스킬이다.
코드를 간결하게 쓸 수 있기 때문에 유용하다.
list comprehension
우선 아래와 같이 대문자 string들을 가진 list가 하나 있다고 하자.
아래 list들의 element들을 모두 소문자로 바꾸고 싶다면, 아래와 같은 for 문을 사용할 수 있다.
number_list = ["FIRST", "SECOND", "THIRD"]
lower_case_list = []
for number in number_list:
lower_case_list.append(number.lower())
print(lower_case_list)
결과는 이렇게 나타난다.
이제 list comprehension을 이용해서 이 코드를 줄여본다.
작성 방법은 이렇게 하면 된다.
: [<적용할 식> for element in List]
List 안에 있는 element를 for 문을 돌리면서 <적용할 식>을 거쳐 list로 반환한다.
# convert into list conprehension
new_lower_case_list = [num.lower() for num in number_list]
print(new_lower_case_list)
결과는 처음의 결과와 같다.
참고로 list가 아닌 string에서 이렇게 응용할 수 있다.
# string list comprehension
sample = "Hello This is my blog"
print([ch for ch in sample])
"Hello This is my blog"라고 적인 string을 담은 sample이라는 변수를 돌면서 문자를 list로 반환한다.
결과는 위와 같다.
그런데 공백은 출력이 되지 않았으면 한다.
그럴 때 사용하는 게 conditional list comprehension이다.
for 문을 적용하면서 if 로 조건을 간단하게 줄 수 있다.
예를 들어 공백을 지우려면 다음과 같이 조건을 줄 수 있다.
# string list comprehension
sample = "Hello This is my blog"
# print([ch for ch in sample])
print([ch for ch in sample if ch != ' '])
if 뒤에 있는 조건에 해당하면, sample을 돌면서 list로 반환한다.
결과를 살펴보면, 공백은 제외하고 list에 저장이 된 것을 확인할 수 있다.
dictionary comprehension
dictionary는 key와 value로 이루어진 data type이다.
# dictionary comprehension
country_city_dict = {
"Korea": 'seoul',
"Japan": 'TOKYO',
"China": 'beijing'
}
예를 들어서 이런 dictionary가 있다고 해보자.
이 dictionary에서 하고 싶은 것은, 소문자로 써진 city를 가진 key와 value만을 가진 dictionary를 생성하는 것이다.
일반적으로 for 문을 사용한다면 아래와 같이 할 수 있을 것 같다.
lower_country_city_dict = {}
for key, value in country_city_dict.items():
if value == value.lower():
lower_country_city_dict[key] = value
print(lower_country_city_dict)
for 문을 돌면서 value를 검사하고, 조건에 해당한다면 key와 value를 추가해 주었다.
결과는 당연히 위와 같다.
이를 dictionary comprehension으로 표현하면 아래처럼 쓸 수 있다.
country_city_dict = {country: city for (country, city) in country_city_dict.items() \
if city == city.lower()}
print(country_city_dict)
비교적 간결한 코드가 되었다.
참고로 여기에서 '\' 표시는 코드가 길어져서 줄 바꿈을 해서 쓰기 위해 집어넣은 것이다.
저렇게 쓰면 Python이 여기서 코드가 줄바꿈 되었다는 것을 인식한다.
그나저나 .. 앞으로도 정리할 게 산더미인데 언제 한다냐.. 끝.
'Pyhon 기초, 실전' 카테고리의 다른 글
[Python 기초] map: 아는 사람만 쓰는 built-in function (0) | 2023.07.19 |
---|---|
[Python 기초] 날짜 및 시간 다루기: datetime module 소개 (0) | 2023.07.18 |
[Python 기초] 여러 가지 파일 읽고 쓰기 (txt, csv, pickle, json 등) (0) | 2023.07.16 |
[Python 기초] set과 tuple 그리고 tuple의 packing, unpacking (0) | 2023.07.14 |
[Python 기초] 주석(Docstring) 작성 스타일 (0) | 2023.07.13 |