
※ set (집합)
순서와 중복이 없는 데이터 구조입니다. 내부적으로 해시(Hash)를 이용해 저장되기 때문에 빠른 탐색이 가능합니다.
s = {1, 2, 3, 3, 4}
print(s) # {1, 2, 3, 4}
s.add(5)
print(s) # {1, 2, 3, 4, 5}
s.remove(2)
print(s) # {1, 3, 4, 5}
→ 중복이 허용되지 않고, 합집합/교집합/차집합 연산을 지원합니다.
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5} (합집합)
print(a & b) # {3} (교집합)
print(a - b) # {1, 2} (차집합)
※ dict (딕셔너리)
key : value 쌍으로 데이터를 저장하는 자료형입니다. key는 중복 불가능하며, 검색과 수정이 빠릅니다.
person = {"name": "지우", "age": 26}
print(person["name"]) # 지우
print(person.get("gender")) # None
print(person.get("gender", "남자")) # 기본값 설정 가능
person["age"] = 27 # 수정
person["gender"] = "남자" # 추가
print(person)
→ dict는 순회하면 기본적으로 key가 리턴됩니다.
for key in person:
print(key, ":", person[key])
※ collections 모듈
파이썬 표준 라이브러리 중 다양한 자료 구조를 제공하는 모듈입니다.
1) deque
양쪽 끝에서 삽입/삭제가 가능한 자료 구조. 큐(Queue)와 스택(Stack) 구현에 유용합니다.
from collections import deque
dq = deque([1, 2, 3])
dq.appendleft(0) # 왼쪽에 삽입
dq.append(4) # 오른쪽에 삽입
print(dq) # deque([0, 1, 2, 3, 4])
dq.pop() # 오른쪽에서 꺼내기
dq.popleft() # 왼쪽에서 꺼내기
print(dq) # deque([1, 2, 3])
2) Counter
데이터의 빈도수를 쉽게 계산할 수 있는 자료형입니다.
from collections import Counter
fruits = ["사과", "바나나", "사과", "딸기", "바나나", "사과"]
counter = Counter(fruits)
print(counter) # Counter({'사과': 3, '바나나': 2, '딸기': 1})
print(counter.most_common(1)) # [('사과', 3)]
3) defaultdict
기존 dict는 없는 key에 접근하면 오류가 발생하지만, defaultdict는 기본값을 자동으로 생성합니다.
from collections import defaultdict
dd = defaultdict(int)
dd["a"] += 1
dd["b"] += 5
print(dd) # defaultdict(<class 'int'>, {'a': 1, 'b': 5})
→ 리스트를 기본값으로 활용하면 여러 데이터를 하나의 key에 저장할 수도 있습니다.
dd_list = defaultdict(list)
dd_list["fruits"].append("사과")
dd_list["fruits"].append("바나나")
print(dd_list) # defaultdict(<class 'list'>, {'fruits': ['사과', '바나나']})
4) OrderedDict
dict는 Python 3.7 이상부터 입력 순서를 보장하지만, OrderedDict는 명시적으로 순서를 유지하고자 할 때 사용됩니다.
from collections import OrderedDict
od = OrderedDict()
od["a"] = 1
od["b"] = 2
od["c"] = 3
for k, v in od.items():
print(k, v)
※ itertools 모듈
반복(iteration)을 더 강력하게 다룰 수 있도록 도와주는 모듈입니다. 조합, 순열, 무한 반복 등 다양한 기능을 제공합니다.
import itertools
# 순열 (permutations)
print(list(itertools.permutations([1, 2, 3], 2)))
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
# 조합 (combinations)
print(list(itertools.combinations([1, 2, 3], 2)))
# [(1, 2), (1, 3), (2, 3)]
# 누적합 (accumulate)
print(list(itertools.accumulate([1, 2, 3, 4])))
# [1, 3, 6, 10]
→ 코딩테스트, 데이터 분석 등에서 자주 쓰이는 강력한 도구입니다.
'2025 현대오토에버 모빌리티 SW 스쿨(클라우드 2기) > 파이썬 이론' 카테고리의 다른 글
| [Python] 함수(Function) 완벽 이해 (0) | 2025.09.21 |
|---|---|
| [Python] 연산자와 제어문 (0) | 2025.09.21 |
| [Python] 데이터 타입 완벽 정리 (1) – 기본 자료형 (0) | 2025.09.21 |
| [Python] 파이썬 기본 문법과 구성 요소 (0) | 2025.09.21 |
| [Python] 파이썬 개발 환경과 가상 환경 (0) | 2025.09.21 |