🎯 1. 카운팅 패턴 (가장 많이 씀!) ⭐⭐⭐
기본 카운팅
# 패턴 1: get() 사용
arr = [1, 2, 2, 3, 3, 3, 4]
count = {}
for num in arr:
count[num] = count.get(num, 0) + 1
print(count)
# {1: 1, 2: 2, 3: 3, 4: 1}
# 패턴 2: setdefault() 사용
count = {}
for num in arr:
count.setdefault(num, 0)
count[num] += 1
# 패턴 3: defaultdict 사용 (추천!) ⭐
from collections import defaultdict
count = defaultdict(int)
for num in arr:
count[num] += 1
# 패턴 4: Counter 사용 (가장 간단!) ⭐⭐⭐
from collections import Counter
count = Counter(arr)
문자 개수 세기
s = "hello world"
# 방법 1: 딕셔너리
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1
print(char_count)
# {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
# 방법 2: Counter (더 간단!)
from collections import Counter
char_count = Counter(s)
# 가장 많은 문자 찾기
most_common_char, count = char_count.most_common(1)[0]
print(f"{most_common_char}: {count}") # l: 3
# 공백 제외하고 카운팅
char_count = Counter(c for c in s if c != ' ')
단어 빈도수
text = "apple banana apple cherry banana apple"
words = text.split()
# 단어 카운팅
word_count = Counter(words)
print(word_count)
# Counter({'apple': 3, 'banana': 2, 'cherry': 1})
# 가장 많은 단어 상위 2개
top_2 = word_count.most_common(2)
print(top_2)
# [('apple', 3), ('banana', 2)]
# 특정 단어 개수
print(word_count['apple']) # 3
print(word_count['grape']) # 0 (없어도 에러 안 남)
🎯 2. 그룹화 패턴 ⭐⭐⭐
리스트로 그룹화
# 학생을 학년별로 그룹화
students = [
('Alice', 1),
('Bob', 2),
('Charlie', 1),
('David', 2),
('Eve', 3)
]
# 방법 1: 일반 딕셔너리
groups = {}
for name, grade in students:
if grade not in groups:
groups[grade] = []
groups[grade].append(name)
print(groups)
# {1: ['Alice', 'Charlie'], 2: ['Bob', 'David'], 3: ['Eve']}
# 방법 2: setdefault
groups = {}
for name, grade in students:
groups.setdefault(grade, []).append(name)
# 방법 3: defaultdict (가장 깔끔!) ⭐
from collections import defaultdict
groups = defaultdict(list)
for name, grade in students:
groups[grade].append(name)
조건에 따른 그룹화
# 점수대별 그룹화
scores = [
('Alice', 85),
('Bob', 92),
('Charlie', 78),
('David', 95),
('Eve', 88)
]
# 90점대, 80점대, 70점대로 그룹화
grade_groups = defaultdict(list)
for name, score in scores:
grade = score // 10 * 10 # 70, 80, 90
grade_groups[grade].append(name)
print(grade_groups)
# defaultdict(<class 'list'>, {80: ['Alice', 'Eve'], 90: ['Bob', 'David'], 70: ['Charlie']})
# A, B, C 등급으로
def get_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
else:
return 'C'
letter_groups = defaultdict(list)
for name, score in scores:
letter_groups[get_grade(score)].append(name)
print(letter_groups)
# defaultdict(<class 'list'>, {'B': ['Alice', 'Eve'], 'A': ['Bob', 'David'], 'C': ['Charlie']})
첫 글자별 그룹화
words = ['apple', 'banana', 'avocado', 'blueberry', 'cherry', 'apricot']
# 첫 글자로 그룹화
first_letter_groups = defaultdict(list)
for word in words:
first_letter_groups[word[0]].append(word)
print(first_letter_groups)
# defaultdict(<class 'list'>, {'a': ['apple', 'avocado', 'apricot'],
# 'b': ['banana', 'blueberry'],
# 'c': ['cherry']})
# 길이별 그룹화
length_groups = defaultdict(list)
for word in words:
length_groups[len(word)].append(word)
print(length_groups)
# defaultdict(<class 'list'>, {5: ['apple'], 6: ['banana', 'cherry'],
# 7: ['avocado', 'apricot'], 9: ['blueberry']})
🎯 3. 인덱싱/매핑 패턴 ⭐⭐⭐
값 → 인덱스 매핑