🐍
Python 치트시트
초보자를 위한 Python 핵심 문법과 라이브러리 가이드
기초 문법자료구조함수 & 클래스데이터 라이브러리웹 / 파일 / 자동화시각화 & 유틸리티
📦
변수와 데이터 타입
변수 선언과 기본 데이터 타입 (선언 키워드 불필요)
기본 타입
# 변수 (선언 키워드 불필요, 타입 자동 추론)
name = "Alice" # str (문자열)
age = 30 # int (정수)
height = 5.7 # float (실수)
is_active = True # bool (불리언)
nothing = None # NoneType (없음)
# 타입 확인
type(name) # <class 'str'>
isinstance(age, int) # True
# 여러 변수 동시 할당
x, y, z = 1, 2, 3
a = b = c = 0타입 변환
int("42") # 42 (문자→정수)
str(100) # "100" (정수→문자)
float("3.14") # 3.14 (문자→실수)
bool(0) # False (0은 False)
bool("hello") # True (비어있지 않으면 True)
list("abc") # ['a', 'b', 'c']
tuple([1, 2]) # (1, 2)📝
문자열 다루기
문자열 포맷팅, 메서드, 슬라이싱
문자열 포맷팅
name = "Alice"
age = 30
# f-string (권장, Python 3.6+)
greeting = f"안녕하세요, {name}! 나이: {age}세"
pi_str = f"π ≈ {3.14159:.2f}" # 소수점 2자리
# format() 메서드
"{} + {} = {}".format(1, 2, 3) # "1 + 2 = 3"
"{name}님".format(name="Bob") # "Bob님"유용한 문자열 메서드
s = " Hello, World! "
s.strip() # "Hello, World!" (공백 제거)
s.lower() # " hello, world! "
s.upper() # " HELLO, WORLD! "
s.replace("o", "0") # " Hell0, W0rld! "
s.split(",") # [' Hello', ' World! ']
",".join(["a","b","c"]) # "a,b,c"
"hello".startswith("he") # True
"hello".endswith("lo") # True
"hello world".count("l") # 3
" ".strip() == "" # True (공백만 있으면 빈 문자열)문자열 슬라이싱
s = "Python"
# P y t h o n
# 인덱스 0 1 2 3 4 5
# 역인덱스 -6 -5 -4 -3 -2 -1
s[0] # 'P' (첫 번째)
s[-1] # 'n' (마지막)
s[1:4] # 'yth' (1~3)
s[:3] # 'Pyt' (처음~2)
s[3:] # 'hon' (3~끝)
s[::-1] # 'nohtyP' (역순)
len(s) # 6🔢
연산자
산술, 비교, 논리, 할당 연산자
연산자 종류
# 산술 연산자
10 + 3 # 13 (더하기)
10 - 3 # 7 (빼기)
10 * 3 # 30 (곱하기)
10 / 3 # 3.333... (나누기)
10 // 3 # 3 (몫)
10 % 3 # 1 (나머지)
2 ** 10 # 1024 (거듭제곱)
# 비교 연산자
5 == 5 # True (같음)
5 != 4 # True (다름)
5 > 3 # True (크다)
5 >= 5 # True (크거나 같다)
# 논리 연산자
True and False # False
True or False # True
not True # False
# 할당 단축
x = 10
x += 5 # x = 15
x -= 3 # x = 12
x *= 2 # x = 24
x //= 5 # x = 4🔀
조건문 (if / elif / else)
조건에 따라 코드 실행 분기
기본 if문
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"점수: {score}, 등급: {grade}") # 점수: 85, 등급: B
# 삼항 연산자 (한 줄 조건)
result = "짝수" if score % 2 == 0 else "홀수"멤버십 & 동일성 테스트
fruits = ["apple", "banana", "cherry"]
"apple" in fruits # True (포함 여부)
"grape" not in fruits # True (미포함 여부)
# None 비교는 is 사용
x = None
x is None # True (권장)
x == None # True (비권장)
# 축약 비교
1 < 5 < 10 # True (연속 비교)
0 <= x <= 100 # 범위 체크 (x=None이면 TypeError)🔁
반복문 (for / while)
for 루프, while 루프, break/continue
for 루프
# range 사용
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(2, 10, 2):
print(i) # 2, 4, 6, 8
# 리스트 순회
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 인덱스와 함께 (enumerate)
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}") # 0: apple, 1: banana, ...
# 딕셔너리 순회
person = {"name": "Alice", "age": 30}
for key, value in person.items():
print(f"{key}: {value}")while / break / continue
# while 루프
count = 0
while count < 5:
print(count)
count += 1
# break: 루프 종료
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
# continue: 현재 반복 건너뜀
for i in range(5):
if i == 2:
continue
print(i) # 0, 1, 3, 4
# zip: 두 리스트 동시 순회
names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]
for name, score in zip(names, scores):
print(f"{name}: {score}")🛡️
에러 처리 (try / except)
예외 처리로 안전한 코드 작성
try / except / finally
# 기본 에러 처리
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"에러 발생: {e}")
# 여러 예외 처리
try:
num = int("abc")
result = 10 / num
except ValueError:
print("숫자로 변환 불가")
except ZeroDivisionError:
print("0으로 나눌 수 없음")
except Exception as e: # 모든 예외 포착
print(f"기타 에러: {e}")
else:
print("에러 없이 성공!") # try 성공 시 실행
finally:
print("항상 실행됨") # 에러 유무 관계없이 실행자주 발생하는 에러 타입
# ValueError: 잘못된 값
int("hello") # ValueError
# TypeError: 잘못된 타입
"abc" + 123 # TypeError
# IndexError: 범위 초과
[1, 2, 3][10] # IndexError
# KeyError: 없는 키
{"a": 1}["b"] # KeyError
# 안전하게: dict.get("b", "기본값")
# AttributeError: 없는 속성
"hello".nonexistent() # AttributeError
# FileNotFoundError: 파일 없음
open("없는파일.txt") # FileNotFoundError📋
리스트 (List)
순서 있고, 변경 가능한 데이터 모음
리스트 기본 조작
fruits = ["apple", "banana", "cherry"]
# 추가
fruits.append("date") # 끝에 추가
fruits.insert(1, "avocado") # 특정 위치에 삽입
fruits.extend(["fig", "grape"]) # 여러 개 추가
# 삭제
fruits.remove("banana") # 값으로 삭제
fruits.pop() # 마지막 삭제 (반환)
fruits.pop(0) # 인덱스로 삭제
del fruits[0] # 인덱스로 삭제
# 조회
fruits[0] # 첫 번째
fruits[-1] # 마지막
fruits[1:3] # 슬라이싱
len(fruits) # 길이
"apple" in fruits # 포함 여부
# 정렬
fruits.sort() # 원본 정렬 (오름차순)
fruits.sort(reverse=True) # 내림차순
sorted(fruits) # 새 리스트로 반환리스트 컴프리헨션
# [표현식 for 변수 in 이터러블 if 조건]
# 기본
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 조건 필터링
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 문자열 변환
words = ["hello", "world", "python"]
upper_words = [w.upper() for w in words]
# 중첩 (flatten)
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [n for row in matrix for n in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]🔒
튜플 & 세트
불변 순서열(tuple)과 고유 값 집합(set)
튜플 (Tuple) - 변경 불가
# 튜플: 괄호 사용, 변경 불가 (immutable)
point = (3, 4)
rgb = (255, 128, 0)
# 언패킹
x, y = point # x=3, y=4
r, g, b = rgb
# 길이, 인덱스
len(point) # 2
point[0] # 3
# 활용: 함수에서 여러 값 반환
def get_min_max(lst):
return min(lst), max(lst)
lo, hi = get_min_max([3, 1, 4, 1, 5, 9])
# lo=1, hi=9세트 (Set) - 고유 값
# 세트: 중복 없음, 순서 없음
colors = {"red", "green", "blue"}
nums = {1, 2, 3, 2, 1} # {1, 2, 3} (중복 제거)
# 추가/삭제
colors.add("yellow")
colors.discard("red") # 없어도 에러 없음
colors.remove("green") # 없으면 KeyError
# 집합 연산
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a | b # 합집합: {1, 2, 3, 4, 5, 6}
a & b # 교집합: {3, 4}
a - b # 차집합: {1, 2}
a ^ b # 대칭차: {1, 2, 5, 6}
# 리스트 중복 제거
items = [1, 2, 2, 3, 3, 3]
unique = list(set(items)) # [1, 2, 3]🗂️
딕셔너리 (Dict)
키-값 쌍의 데이터 구조
딕셔너리 기본
person = {"name": "Alice", "age": 30, "city": "Seoul"}
# 조회
person["name"] # "Alice"
person.get("phone", "없음") # "없음" (기본값 지정 가능)
# 추가/수정
person["email"] = "[email protected]"
person["age"] = 31 # 수정
# 삭제
del person["city"]
popped = person.pop("age") # 삭제하고 반환
# 순회
for key in person.keys():
print(key)
for value in person.values():
print(value)
for key, value in person.items():
print(f"{key}: {value}")
# 키 존재 확인
"name" in person # True딕셔너리 활용 패턴
# 딕셔너리 컴프리헨션
squares = {x: x**2 for x in range(6)}
# {0:0, 1:1, 2:4, 3:9, 4:16, 5:25}
# 딕셔너리 병합 (Python 3.9+)
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
merged = d1 | d2 # {"a":1, "b":3, "c":4}
# setdefault: 키 없을 때만 기본값 설정
d = {}
d.setdefault("count", 0)
d["count"] += 1
# 딕셔너리로 그룹핑
words = ["apple", "ant", "bat", "bear", "cat"]
groups = {}
for word in words:
key = word[0]
groups.setdefault(key, []).append(word)
# {'a':['apple','ant'], 'b':['bat','bear'], 'c':['cat']}⚙️
함수 (Function)
def로 함수 정의, 재사용 가능한 코드 블록
함수 정의와 매개변수
# 기본 함수
def greet(name):
"""독스트링: 함수 설명 (선택사항)"""
return f"안녕하세요, {name}!"
greet("Alice") # "안녕하세요, Alice!"
# 기본값 매개변수
def power(base, exp=2):
return base ** exp
power(3) # 9 (exp 기본값 2 사용)
power(2, 10) # 1024
# 키워드 인수
def describe(name, age, city="서울"):
return f"{name}, {age}세, {city}"
describe("Bob", 25)
describe(age=30, name="Eve", city="부산")*args와 **kwargs
# *args: 가변 위치 인수 (튜플)
def total(*args):
return sum(args)
total(1, 2, 3) # 6
total(1, 2, 3, 4, 5) # 15
# **kwargs: 가변 키워드 인수 (딕셔너리)
def profile(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
profile(name="Alice", age=30, job="개발자")
# 혼합 사용
def mixed(x, *args, **kwargs):
print(x, args, kwargs)
mixed(1, 2, 3, key="value")
# 1 (2, 3) {'key': 'value'}람다 (Lambda) 함수
# lambda: 한 줄 익명 함수
square = lambda x: x ** 2
square(5) # 25
add = lambda x, y: x + y
add(3, 4) # 7
# 정렬에 활용 (key 함수)
words = ["banana", "apple", "cherry", "fig"]
sorted(words, key=lambda w: len(w))
# ['fig', 'apple', 'banana', 'cherry']
students = [{"name": "Bob", "score": 85},
{"name": "Alice", "score": 92}]
sorted(students, key=lambda s: s["score"], reverse=True)
# Alice 먼저 (score 내림차순)🏗️
클래스 (Class)
객체지향 프로그래밍의 기본 단위
클래스 기본
class Dog:
# 클래스 변수 (모든 인스턴스 공유)
species = "Canis familiaris"
# 생성자 (__init__)
def __init__(self, name, age):
self.name = name # 인스턴스 변수
self.age = age
# 인스턴스 메서드
def bark(self):
return f"{self.name}이 짖어요: 멍멍!"
# __str__: print()에서 호출됨
def __str__(self):
return f"Dog({self.name}, {self.age}세)"
# 인스턴스 생성
rex = Dog("Rex", 5)
buddy = Dog("Buddy", 3)
print(rex.bark()) # "Rex이 짖어요: 멍멍!"
print(rex) # "Dog(Rex, 5세)"
rex.name # "Rex"
Dog.species # "Canis familiaris"상속 (Inheritance)
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("하위 클래스에서 구현하세요")
def __str__(self):
return f"{self.__class__.__name__}({self.name})"
class Dog(Animal):
def speak(self):
return f"{self.name}: 멍멍!"
class Cat(Animal):
def speak(self):
return f"{self.name}: 야옹!"
# 다형성: 동일한 메서드, 다른 동작
animals = [Dog("Rex"), Cat("Whiskers"), Dog("Buddy")]
for animal in animals:
print(animal.speak())
# super(): 부모 클래스 호출
class GoldenRetriever(Dog):
def __init__(self, name, color):
super().__init__(name) # 부모 __init__ 호출
self.color = color🔢
NumPy - 수치 계산
배열 연산과 수학 함수의 기본 라이브러리
배열 생성과 기본 연산
import numpy as np
# 배열 생성
a = np.array([1, 2, 3, 4, 5])
b = np.array([10, 20, 30, 40, 50])
# 요소별 연산 (브로드캐스팅)
a + b # [11, 22, 33, 44, 55]
a * 2 # [2, 4, 6, 8, 10]
a ** 2 # [1, 4, 9, 16, 25]
# 통계 함수
np.mean(a) # 3.0 (평균)
np.std(a) # 1.41 (표준편차)
np.min(a) # 1
np.max(a) # 5
np.sum(a) # 152D 배열과 reshape
import numpy as np
# 2D 배열
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
matrix.shape # (3, 3)
matrix[1][2] # 6 (2행 3열)
matrix[0, :] # [1, 2, 3] (첫 번째 행)
matrix[:, 0] # [1, 4, 7] (첫 번째 열)
# 자주 쓰는 배열 생성
np.zeros((3, 4)) # 0으로 채운 3x4 배열
np.ones((2, 3)) # 1로 채운 2x3 배열
np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
np.linspace(0, 1, 5) # [0, 0.25, 0.5, 0.75, 1.0]
np.random.rand(3, 3) # 0~1 랜덤 3x3 배열🐼
Pandas - 데이터 분석
표 형태 데이터를 다루는 핵심 라이브러리
DataFrame 생성과 기본 조작
import pandas as pd
# DataFrame 생성
df = pd.DataFrame({
"이름": ["Alice", "Bob", "Charlie", "David"],
"나이": [25, 30, 35, 28],
"점수": [85, 92, 78, 96],
"도시": ["서울", "부산", "대구", "서울"],
})
# 기본 정보
df.shape # (4, 4) - 행, 열
df.info() # 각 열 타입 및 결측치
df.describe() # 수치 열 통계 요약
df.head(2) # 처음 2행
df.tail(2) # 마지막 2행
# 열 선택
df["이름"] # Series (단일 열)
df[["이름", "점수"]] # DataFrame (여러 열)필터링, 그룹화, CSV 읽기
import pandas as pd
df = pd.read_csv("data.csv") # CSV 읽기
df.to_csv("output.csv", index=False) # CSV 저장
# 조건 필터링
high_score = df[df["점수"] >= 90]
seoul = df[df["도시"] == "서울"]
multi = df[(df["나이"] > 25) & (df["점수"] > 80)]
# 새 열 추가
df["등급"] = df["점수"].apply(lambda x: "A" if x >= 90 else "B")
# 그룹화 집계
df.groupby("도시")["점수"].mean() # 도시별 평균 점수
df.groupby("도시").agg({"점수": ["mean", "max"], "나이": "count"})
# 결측치 처리
df.isnull().sum() # 결측치 개수
df.dropna() # 결측치 행 제거
df.fillna(0) # 결측치를 0으로 채움
df["점수"].fillna(df["점수"].mean()) # 평균으로 채움🌐
Requests - HTTP 요청
웹 API와 통신하는 가장 간단한 방법
GET / POST 요청
import requests
# GET 요청
response = requests.get("https://api.example.com/users")
print(response.status_code) # 200
data = response.json() # JSON 파싱
# 쿼리 파라미터
params = {"page": 1, "limit": 10, "search": "python"}
response = requests.get("https://api.example.com/items", params=params)
# URL: https://api.example.com/items?page=1&limit=10&search=python
# POST 요청 (JSON)
payload = {"username": "alice", "password": "secret"}
response = requests.post("https://api.example.com/login", json=payload)
# 헤더 추가 (인증 등)
headers = {"Authorization": "Bearer YOUR_TOKEN"}
response = requests.get("https://api.example.com/me", headers=headers)에러 처리와 타임아웃
import requests
try:
response = requests.get(
"https://api.example.com/data",
timeout=5 # 5초 타임아웃
)
response.raise_for_status() # 4xx, 5xx 에러 시 예외 발생
data = response.json()
except requests.exceptions.Timeout:
print("요청 시간 초과")
except requests.exceptions.HTTPError as e:
print(f"HTTP 에러: {e.response.status_code}")
except requests.exceptions.ConnectionError:
print("연결 실패")
except requests.exceptions.RequestException as e:
print(f"요청 실패: {e}")🍶
Flask - 웹 프레임워크
간단하고 유연한 Python 웹 프레임워크
기본 Flask 앱
from flask import Flask, request, jsonify
app = Flask(__name__)
# GET 라우트
@app.route("/")
def index():
return "<h1>Hello, Flask!</h1>"
# 동적 URL
@app.route("/users/<int:user_id>")
def get_user(user_id):
return jsonify({"id": user_id, "name": "Alice"})
# POST 요청
@app.route("/users", methods=["POST"])
def create_user():
data = request.get_json()
name = data.get("name", "Unknown")
return jsonify({"created": name}), 201
if __name__ == "__main__":
app.run(debug=True) # python app.py 로 실행⚡
FastAPI - 현대적 API
빠르고 타입 안전한 REST API 프레임워크
FastAPI 기본 구조
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
# 데이터 모델 (자동 검증)
class Item(BaseModel):
name: str
price: float
description: Optional[str] = None
# GET 엔드포인트
@app.get("/")
async def root():
return {"message": "Hello World"}
# 경로 파라미터
@app.get("/items/{item_id}")
async def get_item(item_id: int):
if item_id == 0:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
# POST 엔드포인트 (자동 JSON 파싱)
@app.post("/items/")
async def create_item(item: Item):
return {"name": item.name, "price": item.price}
# 실행: uvicorn main:app --reload
# 문서: http://localhost:8000/docs📁
파일 읽기/쓰기
파일 열기, 읽기, 쓰기 기본 패턴
텍스트 파일 조작
# 파일 쓰기
with open("output.txt", "w", encoding="utf-8") as f:
f.write("첫 번째 줄
")
f.write("두 번째 줄
")
f.writelines(["세 번째
", "네 번째
"])
# 파일 읽기
with open("output.txt", "r", encoding="utf-8") as f:
content = f.read() # 전체 읽기
# 또는
lines = f.readlines() # 줄 단위 리스트
# 또는
for line in f: # 줄 단위 순회 (메모리 효율)
print(line.strip())
# 파일 추가 (append)
with open("output.txt", "a", encoding="utf-8") as f:
f.write("추가된 줄
")pathlib - 경로 다루기
from pathlib import Path
# 경로 생성
p = Path("data/report.csv")
home = Path.home() # 홈 디렉토리
cwd = Path.cwd() # 현재 디렉토리
# 경로 정보
p.name # "report.csv"
p.stem # "report"
p.suffix # ".csv"
p.parent # Path("data")
p.exists() # 파일 존재 여부
# 경로 조작
new_path = p.parent / "archive" / p.name # 경로 합치기
p.read_text(encoding="utf-8") # 파일 읽기
p.write_text("내용", encoding="utf-8") # 파일 쓰기
# 디렉토리 작업
Path("new_dir").mkdir(parents=True, exist_ok=True)
list(Path(".").glob("*.py")) # .py 파일 목록
list(Path(".").rglob("*.txt")) # 재귀적으로 .txt 파일📊
JSON & CSV
데이터 파일 형식 읽기/쓰기
JSON 처리
import json
# Python → JSON 문자열
data = {"name": "Alice", "scores": [95, 87, 92], "active": True}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
# JSON 문자열 → Python
parsed = json.loads(json_str)
parsed["name"] # "Alice"
# JSON 파일 읽기
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
# JSON 파일 쓰기
with open("output.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)CSV 처리
import csv
# CSV 읽기 (DictReader: 헤더를 키로 사용)
with open("data.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["age"])
# row는 딕셔너리: {"name": "Alice", "age": "30"}
# CSV 쓰기
data = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
]
with open("output.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age"])
writer.writeheader()
writer.writerows(data)🤖
Selenium - 브라우저 자동화
웹 브라우저를 자동으로 제어하고 스크래핑
기본 사용법
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 브라우저 시작
driver = webdriver.Chrome()
driver.get("https://www.google.com")
# 요소 찾기
search_box = driver.find_element(By.NAME, "q")
search_box.send_keys("Python 튜토리얼")
search_box.send_keys(Keys.RETURN)
# 대기 (요소가 나타날 때까지)
wait = WebDriverWait(driver, 10)
results = wait.until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, "h3"))
)
for result in results[:5]:
print(result.text)
driver.quit()⏰
Schedule - 작업 스케줄링
반복 작업을 정해진 시간에 자동 실행
schedule 라이브러리
import schedule
import time
from datetime import datetime
def backup_data():
print(f"[{datetime.now()}] 데이터 백업 실행")
def send_report():
print(f"[{datetime.now()}] 보고서 전송")
def cleanup():
print("임시 파일 정리")
# 스케줄 설정
schedule.every(10).seconds.do(backup_data) # 10초마다
schedule.every(5).minutes.do(backup_data) # 5분마다
schedule.every().hour.do(backup_data) # 1시간마다
schedule.every().day.at("09:00").do(send_report) # 매일 9시
schedule.every().monday.do(cleanup) # 매주 월요일
# 실행 루프
while True:
schedule.run_pending()
time.sleep(1)📈
Matplotlib - 그래프 그리기
데이터를 다양한 차트와 그래프로 시각화
선 그래프, 막대 그래프, 산점도
import matplotlib.pyplot as plt
import numpy as np
# 선 그래프
x = np.linspace(0, 2 * np.pi, 100)
plt.figure(figsize=(10, 4))
plt.plot(x, np.sin(x), label="sin(x)", color="blue")
plt.plot(x, np.cos(x), label="cos(x)", color="red", linestyle="--")
plt.xlabel("x")
plt.ylabel("y")
plt.title("삼각함수 그래프")
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("plot.png") # 파일 저장
plt.show()
# 막대 그래프
categories = ["월", "화", "수", "목", "금"]
values = [12, 19, 7, 15, 22]
plt.bar(categories, values, color="steelblue")
plt.title("요일별 방문자 수")
plt.show()🎨
Seaborn - 통계 시각화
아름다운 통계 그래프를 쉽게 생성
Seaborn 기본 차트
import seaborn as sns
import matplotlib.pyplot as plt
# 예제 데이터셋 로드
tips = sns.load_dataset("tips")
# 산점도 (회귀선 포함)
sns.lmplot(x="total_bill", y="tip", data=tips, height=5)
plt.title("청구금액 vs 팁")
plt.show()
# 박스 플롯
plt.figure(figsize=(10, 5))
sns.boxplot(x="day", y="total_bill", data=tips, palette="pastel")
plt.title("요일별 청구금액 분포")
plt.show()
# 히트맵 (상관관계)
plt.figure(figsize=(8, 6))
corr = tips.select_dtypes("number").corr()
sns.heatmap(corr, annot=True, cmap="coolwarm", center=0)
plt.title("상관관계 히트맵")
plt.show()
# 히스토그램 + KDE
sns.histplot(tips["total_bill"], kde=True, bins=20)
plt.show()📅
datetime - 날짜와 시간
날짜, 시간 처리와 계산
날짜/시간 기본
from datetime import datetime, date, timedelta
# 현재 시간
now = datetime.now() # 현재 날짜 + 시간
today = date.today() # 오늘 날짜만
# 특정 날짜/시간 생성
dt = datetime(2024, 12, 25, 14, 30, 0)
# 포맷팅 (strftime)
now.strftime("%Y-%m-%d") # "2024-03-24"
now.strftime("%Y년 %m월 %d일") # "2024년 03월 24일"
now.strftime("%H:%M:%S") # "14:30:00"
# 파싱 (strptime)
dt = datetime.strptime("2024-03-24", "%Y-%m-%d")
dt = datetime.strptime("24/03/2024 14:30", "%d/%m/%Y %H:%M")
# 날짜 계산
tomorrow = today + timedelta(days=1)
next_week = today + timedelta(weeks=1)
three_hours_later = now + timedelta(hours=3)
# 날짜 차이
diff = datetime(2024, 12, 31) - datetime.now()
print(f"D-{diff.days}") # 크리스마스까지 며칠🗃️
collections - 특수 컨테이너
Counter, defaultdict, namedtuple 등 유용한 자료구조
Counter, defaultdict, namedtuple
from collections import Counter, defaultdict, namedtuple, deque
# Counter: 개수 세기
words = ["apple", "banana", "apple", "cherry", "apple", "banana"]
counter = Counter(words)
# Counter({'apple': 3, 'banana': 2, 'cherry': 1})
counter.most_common(2) # [('apple', 3), ('banana', 2)]
Counter("hello") # Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
# defaultdict: 기본값 있는 딕셔너리
dd = defaultdict(list)
dd["fruits"].append("apple") # KeyError 없음!
dd["fruits"].append("banana")
# {'fruits': ['apple', 'banana']}
word_lengths = defaultdict(int)
for word in words:
word_lengths[word] += 1
# namedtuple: 이름 있는 튜플
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
p.x, p.y # 3, 4
p[0], p[1] # 3, 4 (인덱스도 가능)
# deque: 양방향 큐
d = deque([1, 2, 3])
d.appendleft(0) # [0, 1, 2, 3]
d.popleft() # 0 반환🔄
itertools - 반복자 도구
효율적인 반복 처리를 위한 함수 모음
유용한 itertools 함수
from itertools import (
chain, product, combinations,
permutations, groupby, islice, cycle
)
# chain: 여러 이터러블 연결
list(chain([1, 2], [3, 4], [5]))
# [1, 2, 3, 4, 5]
# product: 데카르트 곱
list(product("AB", "12"))
# [('A','1'), ('A','2'), ('B','1'), ('B','2')]
# combinations: 조합
list(combinations([1,2,3,4], 2))
# [(1,2), (1,3), (1,4), (2,3), (2,4), (3,4)]
# permutations: 순열
list(permutations([1,2,3], 2))
# [(1,2), (1,3), (2,1), (2,3), (3,1), (3,2)]
# islice: 이터레이터 슬라이싱
list(islice(range(100), 5)) # [0, 1, 2, 3, 4]
# cycle: 무한 반복 (islice로 잘라씀)
colors = list(islice(cycle(["red","green","blue"]), 7))
# ['red','green','blue','red','green','blue','red']🔍
re - 정규 표현식
패턴 매칭으로 텍스트 검색, 추출, 변환
정규 표현식 기본
import re
text = "연락처: [email protected], 전화: 010-1234-5678"
# 검색 (첫 번째 매치)
match = re.search(r'\d{3}-\d{4}-\d{4}', text)
if match:
print(match.group()) # "010-1234-5678"
# 모든 매치 찾기
emails = re.findall(r'[\w.]+@[\w.]+\.[\w]+', text)
# ['[email protected]']
# 치환
clean = re.sub(r'\d', '*', "카드번호: 1234-5678")
# "카드번호: ****-****"
# 분할
parts = re.split(r'[,;\s]+', "one, two; three four")
# ['one', 'two', 'three', 'four']
# 자주 쓰는 패턴
# \d 숫자 [0-9]
# \w 단어문자 [a-zA-Z0-9_]
# \s 공백 문자
# . 임의의 문자 (줄바꿈 제외)
# * 0개 이상
# + 1개 이상
# ? 0개 또는 1개
# ^ 문자열 시작
# $ 문자열 끝⚡
한 줄 패턴 모음
자주 쓰는 Python 한 줄 코드 패턴
자주 쓰는 패턴
# 리스트 최대/최소 인덱스
lst = [3, 1, 4, 1, 5, 9, 2, 6]
max_idx = lst.index(max(lst)) # 5
# 리스트 평탄화
nested = [[1,2], [3,4], [5,6]]
flat = sum(nested, []) # [1,2,3,4,5,6]
# 딕셔너리 뒤집기
d = {"a": 1, "b": 2, "c": 3}
inv = {v: k for k, v in d.items()} # {1:'a', 2:'b', 3:'c'}
# 문자열 팰린드롬 체크
is_palindrome = lambda s: s == s[::-1]
is_palindrome("racecar") # True
# 파일 한 번에 읽기
content = open("file.txt", encoding="utf-8").read()
# 중복 제거 (순서 유지)
seen = set()
unique = [x for x in lst if not (x in seen or seen.add(x))]
# 딕셔너리 기본값
config = {"debug": True}
port = config.get("port", 8080) # 없으면 8080
# 조건부 리스트 추가
items = []
condition = True
items += ["new_item"] if condition else []내장 함수 핵심 모음
# map: 모든 원소에 함수 적용
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers)) # [1,4,9,16,25]
# filter: 조건에 맞는 원소만
evens = list(filter(lambda x: x%2==0, numbers)) # [2,4]
# zip: 두 리스트를 묶음
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
pairs = list(zip(names, scores)) # [('Alice',85), ...]
to_dict = dict(zip(names, scores)) # {'Alice':85, ...}
# enumerate: 인덱스와 값
for i, name in enumerate(names, start=1):
print(f"{i}. {name}") # 1. Alice, 2. Bob, ...
# any / all: 논리 연산
any(x > 90 for x in scores) # True
all(x > 70 for x in scores) # True
# sorted with key
sorted(names, key=len) # 길이 순: ['Bob','Alice','Charlie']
sorted(names, reverse=True) # 역순: ['Charlie','Bob','Alice']
# min/max with key
min(names, key=len) # 'Bob' (가장 짧은)📦
pip & 가상환경
패키지 설치와 가상환경 관리
pip 명령어
# 패키지 설치
pip install requests # 설치
pip install requests==2.31.0 # 특정 버전
pip install "requests>=2.0,<3.0" # 버전 범위
# 패키지 관리
pip list # 설치된 패키지 목록
pip show requests # 패키지 정보
pip uninstall requests # 제거
pip install --upgrade requests # 업그레이드
# requirements.txt
pip freeze > requirements.txt # 현재 환경 저장
pip install -r requirements.txt # 파일에서 설치가상환경 (venv)
# 가상환경 생성
python -m venv venv # 'venv' 폴더에 생성
python -m venv .venv # 숨김 폴더로
# 활성화
# macOS/Linux:
source venv/bin/activate
# Windows:
venv\Scripts\activate
# 활성화 확인
which python # .../venv/bin/python
# 비활성화
deactivate
# 패키지 설치 (활성화 후)
pip install requests pandas numpy
# 환경 재현
pip freeze > requirements.txt
# 새 환경에서:
pip install -r requirements.txt