TIL | Python - List Comprehensions

송치헌·2021년 8월 10일
0
post-thumbnail

무엇을 배웠는가

list comprehension

리스트를 만들 때 표현되는 간단한 표현식이다. 쉽게 바로 예를 들어서 보면

#보통 list를 만들 때 쓰는 표현
new_list = []
for i in range(10):
    new_list.append(i)
print(new_list)
#result
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#L.C를 이용한 표현
new_LC = [i for i in range(10)]
print(new_LC)
#result
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

if문을 포함하는 list comprehension

1에서 10까지의 수 중 홀수만 순서대로 리스트에 담는 코드는 다음과 같을 것이다.

new_odd_numlist = []
for i in range(1,11,2):
    new_odd_numlist.append(i)

또는

new_odd_numlist_with_if = []
for i in range(1,11):
    if i%2==1:
        new_odd_numlist_with_if.append(i)

LC(list comprehension)을 이용해서 if문을 첨가하여 사용하면 다음과 같이 간단하게 표현 가능하다.

new_odd_numlist_LC = [i for i in range(1,11) if i%2==1]
print(new_odd_numlist_LC)
#result
#[1, 3, 5, 7, 9]

두 문법의 실행시간을 비교하여 보았다.

import timeit

def for_loop():
    num_list = []
    for i in range(1000):
        num_list.append(i)

def list_comprehension():
    num_list = [i for i in range(1000)]

if __name__=="__main__":
    time1 = timeit.Timer("for_loop()", "from __main__ import for_loop")
    print("for loop time=", time1.timeit(number=1000), "milliseconds")

    time2 = timeit.Timer("list_comprehension()", "from __main__ import list_comprehension")
    print("list_comprehension time = ", time2.timeit(number=1000), "milliseconds")
#result
#for loop time= 0.167816771 milliseconds
#list_comprehension time =  0.04621133500000002 milliseconds

list comprehension으로 실행한 것이 약 3.5배정도 더 빨랐다.

어디에 적용했는가

조건이 있는 list comprehensions로 list와 dictionary를 구현해 보았다.

#1
cities = ["Tokyo","Shanghai","Jakarta","Seoul","Guangzhou","Beijing","Karachi","Shenzhen","Delhi"]
no_start_S = [city for city in cities if city[0]!="S"]
print(no_start_S)
#result
#['Tokyo', 'Jakarta', 'Guangzhou', 'Beijing', 'Karachi', 'Delhi']

#2.
population_of_city = [
    ('Tokyo', 36923000), 
    ('Shanghai', 34000000), 
    ('Jakarta', 30000000), 
    ('Seoul', 25514000), 
    ('Guangzhou', 25000000), 
    ('Beijing', 24900000), 
    ('Karachi', 24300000), 
    ('Shenzhen', 23300000), 
    ('Delhi', 21753486) 
    ]

city_dict = {s[0] : s[1] for s in population_of_city}
print(city_dict)
#result
'''
{
  'Tokyo': 36923000, 
  'Shanghai': 34000000, 
  'Jakarta': 30000000, 
  'Seoul': 25514000, 
  'Guangzhou': 25000000, 
  'Beijing': 24900000, 
  'Karachi': 24300000, 
  'Shenzhen': 23300000, 
  'Delhi': 21753486
}
'''

어려웠던 점은 무엇인가

평소 알던 내용이라 어려웠던 점은 없었지만 if를 붙여서 사용하는 부분은 살짝 생소했지만 금방 사용법을 익히게 되었다.
if로 조건을 설정할 수 있으면 else로 다른 조건을 넣을 수도 있지 않을까? 라는 생각에 찾아보니 위에서 익힌 방법과 사용법이 약간 달랐다.

cities = ["Tokyo","Shanghai","Jakarta","Seoul","Guangzhou","Beijing","Karachi","Shenzhen","Delhi"]
no_start_S = [city if city[0]!="S" else "NO" for city in cities]
print(no_start_S)
#result
#'Tokyo', 'NO', 'Jakarta', 'NO', 'Guangzhou', 'Beijing', 'Karachi', 'NO', 'Delhi']

if else문을 먼저 사용한 후 for문을 사용했다. 이런 방법도 있으니 알고 가면 좋을 것 같다.

profile
https://oraange.tistory.com/ 여기에도 많이 놀러와 주세요

0개의 댓글