아직은 위코드 2주차 2일!! 이번엔 python
나름 심화!에 대해서 알아보려한다.
list comprehensions
이란 새로운 리스트를 만들 때 사용할 수 있는 간단한 표현식으로 [ ]
를 사용하여 작성한다.
어떠한 형식으로 작성되는지 살펴보자.
[표현식 for 원소 in 반복 가능한 객체 if 문] # if문 생략 가능
new_list = [ i for i in range(5) if (i % 2) == 1 ]
print(new_list)
> [1,3]
뭔가 어디서 본 듯한 형식이다.
이걸 풀어서 쓰게 되면 아래와 같다.
new_list = []
for i in range(5):
if i % 2 == 1:
new_list.append(i)
print(new_list)
> [1,3]
이 4줄 짜리 코드가 1줄로 줄여질 수 있다는 점에서 for루프 내에서 새로운 리스트를 만들 때 꽤나 유용해 보인다.
list comprehensions
가 어떤 경우에 많이 사용되는가 보니, 데이터베이스를 조회하여 리스트를 만들 때, 새로운 배열을 만들 때 많이 사용한다.
하지만 가독성을 위해 for 문을 사용하는 것이 더 좋을 때도 있다.
dictionary comprehension
dictionary comprehension
도 list comprehension
과 비슷하게 사용할 수 있고, list
를 dictionary comprehension
을 이용해 dictionary
로 바꿀 수도 있다.
dict1 = dict(one=1, two=2, three=3)
dict_comp1 = { k:v * 2 for k,v in dict1.items()}
print(dict1)
> {'one': 1, 'two': 2, 'three': 3}
print(dict_comp)
> {'one': 2, 'two': 4, 'three': 6}
names = ['광일', '광이', '광삼']
dict_comp_names = { n : 'name' for n in names }
print(dict_comp_names)
> {'광일': 'names', '광이': 'names', '광삼': 'names'}
numbers = [('one',1), ('two',2), ('three',3)]
dict_comp_numbers = { k : v for k,v in numbers }
print(dict_comp_numbers)
> {'one': 1, 'two': 2, 'three': 3}
dictionary comprehension + if~
dictionary comprehension
도 list comprehension
처럼 조건문을 걸 수 있다.
scores = {'광일': 40, '광이': 80, '광삼': 90, '광사': 60}
dict_comp_scores = { name : score for name, score in scores.items() if score >= 60 }
print(dict_comp_scores)
> {'광이': 80, '광삼': 90, '광사': 60}
grades = grades = { name: 'PASS' if value > 70 else 'No-PASS' for name, value in scores.items()}
print(grades)
> {'광일': 'No-PASS', '광이': 'PASS', '광삼': 'PASS', '광사': 'No-PASS'}
dictionary comprehension + zip
위에서 했던 list
를 활용하여 dictionary
로 만드는 방법과 비슷하지만, 이 경우엔 list
가 2개가 필요하다.
names = [ '광일', '광둘', '광셋' ]
ages = [ 29, 24, 26]
dict_comp_names = { name : age for name, age in zip(names, ages) }
print(dict_comp_names)
dict_comp_adult = { name : '으른' if age > 25 else '어린이' for name, age in zip(names, ages)}
print(dict_comp_adult)
> {'광일': '으른', '광둘': '어린이', '광셋': '으른'}
내가 참고한 블로그
https://velog.io/@ash3767/jakdu%EB%94%95%EC%85%94%EB%84%88%EB%A6%AC