티스토리 뷰
728x90
반응형
[1] List Comprehension
PEP 202 -- List Comprehensions
The official home of the Python Programming Language
www.python.org
List Comprehension은 기존 리스트를 기반으로 새로운 리스트를 만들어내는 구문입니다.
예를들어 leading and trailing whitespaces를 지워주는 strip을 리스트의 모든 아이템에 적용하고 싶다면
이렇게 리스트 컴프리헨션을 이용할 수 있습니다.
list = ["죠르디 ", " 라이언 "]
new_list = [item.strip() for item in list]
print(new_list)
// 결과
['죠르디', '라이언']
if문도 곁들여서 쓸 수 있습니다.
짝수인 아이템이라면 2를 곱해 새로운 리스트에 넣어주는 예제입니다
list = [1,2,3,4]
new_list = [item * 2 for item in list if item % 2 == 0]
print(new_list)
// 결과
[4, 8]
참고로 아래처럼 map, filter + 람다 표현식을 쓰는 것보다
리스트 컴프리핸션이 가독성이 더 좋고 더 파이써닉한 방법이라고 합니다 +_+
sample_list = ["죠르디 ", " 라이언 "]
new_list = list(map(lambda item: item.strip(), sample_list))
print(new_list)
// 결과
['죠르디', '라이언']
[2] Dict Comprehension
PEP 274 -- Dict Comprehensions
The official home of the Python Programming Language
www.python.org
Dict Comprehension은 기존 딕셔너리를 기반으로 새로운 딕셔너리를 만들어내는 구문입니다.
나이를 value로 저장하고 있는 dictionary에서
나이를 한 살씩 뺀 새로운 dictionary를 만들고 싶다고 해봅시다.
아래의 예제처럼 for문을 돌릴 수 도 있지만 ( items() 메소드로 딕셔너리의 key, value를 각각 꺼낼 수 있습니다 )
age_dict = {"죠르디": 10, "라이언": 20}
new_age_dict = {}
for key, value in age_dict.items():
new_age_dict[key] = value - 1
print(new_age_dict)
// 결과
{'죠르디': 9, '라이언': 19}
Dict Comprehension을 이용해서 코드 라인을 줄일 수 있습니다.
age_dict = {"죠르디": 10, "라이언": 20}
new_age_dict = { key : value - 1 for key, value in age_dict.items() }
print(new_age_dict)
// 결과
{'죠르디': 9, '라이언': 19}
반응형
'🐍 > Python' 카테고리의 다른 글
[Python] defaultdict / Counter / OrderedDict (0) | 2021.04.13 |
---|---|
[Python] f-string (🖐 %-formatting / str.format / string.Template) (0) | 2021.04.09 |
[Python] gitignore 만들고 github에 올리는 스크립트를 작성해보자 (0) | 2021.01.22 |
[Python] 구글 Geocoding API 사용해보기 (3) | 2020.12.21 |
[Python] 파이썬 타입힌트 (Type Hints) (0) | 2020.11.29 |
댓글
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- 구글 Geocoding API
- ipad multitasking
- Django Heroku Scheduler
- METAL
- Flutter Spacer
- Sketch 누끼
- DRF APIException
- flutter deep link
- PencilKit
- drf custom error
- flutter dynamic link
- Django FCM
- github actions
- 장고 Custom Management Command
- Python Type Hint
- ribs
- cocoapod
- 장고 URL querystring
- Watch App for iOS App vs Watch App
- Flutter Text Gradient
- 플러터 얼럿
- Flutter Clipboard
- 플러터 싱글톤
- Flutter 로딩
- Django Firebase Cloud Messaging
- Dart Factory
- flutter build mode
- Flutter getter setter
- SerializerMethodField
- flutter 앱 출시
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함