에듀테크 프로젝트 대시보드
json · itertools · functools · random
실무에서 손이 가장 자주 가는 표준 라이브러리 네 개를 한눈에.
import json
s = json.dumps({"name": "김", "nums": [1, 2]}, ensure_ascii=False, indent=2)
data = json.loads(s) # 문자열 → dict/list
with open("d.json", encoding="utf-8") as f:
data = json.load(f)
with open("out.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# 커스텀 객체는 default= 로 직렬화
json.dumps(obj, default=lambda o: o.__dict__)| JSON | 파이썬 |
|---|---|
| object | dict |
| array | list |
| string | str |
| number | int / float |
| true/false | True / False |
| null | None |
import itertools as it
it.chain([1, 2], [3, 4]) # 1 2 3 4
it.islice(seq, 2, 10, 2) # 슬라이스 (제너레이터)
it.groupby(sorted(rows, key=k), k) # 연속 그룹핑
it.combinations([1, 2, 3], 2) # (1,2) (1,3) (2,3)
it.permutations([1, 2, 3], 2) # 순열
it.product("AB", "12") # A1 A2 B1 B2
it.accumulate([1, 2, 3, 4]) # 1 3 6 10
it.count(0, 2); it.cycle("ab"); it.repeat(9, 3) # 무한 계열from functools import lru_cache, cache, partial, reduce, wraps
@cache # 메모이제이션 (3.9+)
def fib(n): return n if n < 2 else fib(n-1) + fib(n-2)
add = lambda a, b: a + b
inc = partial(add, 1) # inc(10) => 11
reduce(add, [1, 2, 3, 4]) # => 10
from functools import cached_property
class C:
@cached_property # 첫 접근 시 계산 후 저장
def heavy(self): ...import random
random.random() # 0.0 <= x < 1.0
random.uniform(1, 10) # 실수 범위
random.randint(1, 6) # 1~6 정수 (양끝 포함)
random.randrange(0, 100, 5) # range 방식
random.choice(["a", "b", "c"])
random.choices(pop, weights=[1, 1, 8], k=5) # 복원 추출
random.sample(range(100), 6) # 비복원 추출 (로또)
random.shuffle(deck) # 제자리 섞기
random.seed(42) # 재현 가능하게 고정import os, sys, textwrap, statistics, decimal
os.environ.get("HOME")
os.getcwd(); os.path.join("a", "b")
statistics.mean([1, 2, 3]); statistics.median(xs); statistics.stdev(xs)
decimal.Decimal("0.1") + decimal.Decimal("0.2") # 정확히 0.3
textwrap.shorten("긴 텍스트 ...", width=20)
textwrap.dedent(indented_multiline)argparse: CLI 인자 파싱 / logging: 로깅 / unittest·pytest: 테스트