학습 순서
| 순서 | 주제 | 핵심 |
|---|---|---|
| 1 | 변수와 자료형 | int, float, str, bool, 형변환 |
| 2 | 자료구조 | list, tuple, dict, set — 언제 무엇을 쓰는지 |
| 3 | 제어문 | if, for, while, 컴프리헨션 |
| 4 | 함수 | 매개변수, 반환값, lambda, 기본값 인자 |
| 5 | 파일 입출력 | open, with, CSV/JSON 읽고 쓰기 |
| 6 | 모듈과 패키지 | import, pip, 가상환경 |
| 7 | 예외 처리 | try / except / finally |
꼭 익혀야 할 패턴
딕셔너리와 리스트 컴프리헨션
sales = [
{"region": "Seoul", "amount": 120},
{"region": "Busan", "amount": 80},
{"region": "Seoul", "amount": 50},
]
# 지역별 합계 — 나중에 Pandas의 groupby, Spark의 reduceByKey와 같은 개념
totals = {}
for row in sales:
totals[row["region"]] = totals.get(row["region"], 0) + row["amount"]
print(totals) # {'Seoul': 170, 'Busan': 80}
# 컴프리헨션
big = [r for r in sales if r["amount"] >= 100]
파일 읽기 (CSV / JSON)
import csv, json
with open("data.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"], row["score"])
with open("data.json", encoding="utf-8") as f:
data = json.load(f)
함수와 map / filter
MapReduce, Spark의 map/filter/reduce가 바로 이 개념입니다.
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x * x, nums)) # [1, 4, 9, 16, 25]
evens = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4]
from functools import reduce
total = reduce(lambda a, b: a + b, nums) # 15
연습 과제
- 학번·이름·점수가 든 CSV를 읽어서 평균 점수를 출력
- 점수가 80 이상인 학생만 새 CSV로 저장
- 위 작업을 함수로 분리하고 다른 파일에도 재사용
다음 단계(Pandas)에서는 위 작업을 코드 3줄로 줄이는 방법을 배웁니다.