일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- algorithm
- nerf
- GAN
- FineGrained
- SSL
- pytorch
- 자료구조
- dl
- ML
- math
- 3d
- Python
- 머신러닝
- Meta Learning
- Vision
- cs
- FGVC
- computervision
- 딥러닝
- REACT
- nlp
- clean code
- Torch
- CV
- PRML
- classification
- Depth estimation
- 알고리즘
- Front
- web
- Today
- Total
KalelPark's LAB
[ CLEAN CODE ] Clean Python, Dictionary 활용하기 본문
Dictionary
- 파이썬에서 Dictionary를 활용할 때, 어떤 Key에 대한 Value를 처리해야 하는 경우가 상당히 많이 존재합니다.
EX>
def counterLetters(word):
counter = {}
for letter in word:
if letter not in counter:
counter[letter] = 0
counter[letter] += 1
return counter
* 위 코드의 문제는 letter가 counter내에 존재하지 않으면, 초기 세팅을 해주는 코드입니다.
하지만, 위 코드의 문제는 가독성이 상당히 떨어진다는 상당한 문제점이 존재합니다.
Dict.setdefault
- Key와 Value를 인자로 받는 Dictionary의 Method입니다.
원리는 setdefault는 Key가 존재한다면, Key를 반환하고, 없다면, Values를 반환합니다.
위의 코드를 조금 수정해보자면,
def counterletters(word):
counter = {}
for letter in word:
counter.setdefault(letter, 0)
counter[letter] += 1
return counter
* 가독성이 향상되지만, 무조건적으로 setdefault가 호출된다는 문제점이 있습니다.
Collection.defaultdict
- defaultdict은 dictionary의 기본값을 정의하고, 값이 없는 경우 에러를 출력하지 않고, 기본값을 출력합니다.
setdefault보다 빠르다는 장점을 가지고 있습니다.
- 기본값으로 value가 아닌, list, object등 객체를 지정하는 것도 가능합니다.
from collections import defaultdict
def counterLetters(word):
counter = defaultdict(int)
for letter in word:
counter[letter] += 1
return counter
참고
https://www.daleseo.com/python-collections-defaultdict/
[파이썬] 사전의 기본값 처리 (dict.setdefault / collections.defaultdict)
Engineering Blog by Dale Seo
www.daleseo.com
https://gomguard.tistory.com/126
[Python] Dictonary 관련 함수 - setdefault, defaultdict, counter
dict 구성하는 방법 - 기본 s= ['a', 'b', 'c', 'b', 'a', 'b', 'c']dic = {}for i in s: if i not in dic.keys(): dic[i] = 0 dic[i] +=1 print(dic) 기본적으로 dic 을 구성하기 위해선 key 마다 기본값들을 정해준 뒤에야 연산이 가
gomguard.tistory.com
'Python > CLEAN CODE' 카테고리의 다른 글
[ CLEAN CODE ] Clean Python, StaticMethod, ClassMethod란? (0) | 2023.01.13 |
---|---|
[ CLEAN CODE ] Clean Python, Logging 활용하기 (0) | 2023.01.02 |
[ CLEAN CODE ] Clean Python, Property 활용하기 (0) | 2023.01.01 |
[ CLEAN CODE ] Clean Python, Argparse 유용하게 활용하기 (0) | 2022.12.30 |
[ CLEAN CODE ] Clean Python, __future__이란? (0) | 2022.12.28 |