728x90
반응형
안녕하세요! 오늘은 파이썬의 기본 자료 구조에 대해 알아보겠습니다.
파이썬에서 제공하는 다양한 자료 구조를 이해하면 효율적인 코드를 작성하는 데 큰 도움이 됩니다.
1. 리스트(List)
리스트는 파이썬에서 가장 많이 사용되는 자료 구조 중 하나입니다. 순서가 있고 변경 가능한 객체들의 집합입니다.
# 리스트 생성
fruits = ['사과', '바나나', '오렌지', '포도']
# 리스트 요소 접근
print(fruits[0]) # 첫 번째 요소
print(fruits[-1]) # 마지막 요소
# 리스트 슬라이싱
print(fruits[1:3]) # 두 번째부터 세 번째 요소까지
# 리스트 요소 추가
fruits.append('키위')
print(fruits)
# 리스트 요소 삽입
fruits.insert(1, '딸기')
print(fruits)
# 리스트 요소 삭제
fruits.remove('바나나')
print(fruits)
출력 결과:
사과
포도
['바나나', '오렌지']
['사과', '바나나', '오렌지', '포도', '키위']
['사과', '딸기', '바나나', '오렌지', '포도', '키위']
['사과', '딸기', '오렌지', '포도', '키위']
2. 튜플(Tuple)
튜플은 리스트와 유사하지만 한 번 생성하면 변경할 수 없습니다(불변).
# 튜플 생성
coordinates = (10, 20)
person = ('홍길동', 30, '서울')
# 튜플 요소 접근
print(coordinates[0])
print(person[1])
# 튜플 언패킹
name, age, city = person
print(f"이름: {name}, 나이: {age}, 도시: {city}")
# 튜플은 변경 불가능
try:
coordinates[0] = 15
except TypeError as e:
print(f"오류 발생: {e}")
출력 결과:
10
30
이름: 홍길동, 나이: 30, 도시: 서울
오류 발생: 'tuple' object does not support item assignment
3. 딕셔너리(Dictionary)
딕셔너리는 키-값 쌍으로 이루어진 자료 구조입니다.
# 딕셔너리 생성
student = {
'name': '김철수',
'age': 20,
'major': '컴퓨터 공학',
'grades': {'math': 90, 'science': 85, 'programming': 95}
}
# 딕셔너리 요소 접근
print(student['name'])
print(student.get('age'))
print(student['grades']['programming'])
# 딕셔너리 요소 추가/수정
student['email'] = 'kim@example.com'
student['age'] = 21
print(student)
# 딕셔너리 요소 삭제
del student['major']
print(student)
# 키와 값 목록 가져오기
print(student.keys())
print(student.values())
print(student.items())
출력 결과:
김철수
20
95
{'name': '김철수', 'age': 21, 'major': '컴퓨터 공학', 'grades': {'math': 90, 'science': 85, 'programming': 95}, 'email': 'kim@example.com'}
{'name': '김철수', 'age': 21, 'grades': {'math': 90, 'science': 85, 'programming': 95}, 'email': 'kim@example.com'}
dict_keys(['name', 'age', 'grades', 'email'])
dict_values(['김철수', 21, {'math': 90, 'science': 85, 'programming': 95}, 'kim@example.com'])
dict_items([('name', '김철수'), ('age', 21), ('grades', {'math': 90, 'science': 85, 'programming': 95}), ('email', 'kim@example.com')])
4. 집합(Set)
집합은 중복이 없는 요소들의 모음입니다.
# 집합 생성
fruits_set = {'사과', '바나나', '오렌지', '사과'} # 중복은 자동으로 제거됨
numbers = set([1][2][3][4][5])
print(fruits_set)
print(numbers)
# 집합 연산
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 합집합
print(set1 | set2) # 또는 set1.union(set2)
# 교집합
print(set1 & set2) # 또는 set1.intersection(set2)
# 차집합
print(set1 - set2) # 또는 set1.difference(set2)
# 대칭 차집합
print(set1 ^ set2) # 또는 set1.symmetric_difference(set2)
# 요소 추가 및 삭제
fruits_set.add('키위')
print(fruits_set)
fruits_set.remove('바나나')
print(fruits_set)
출력 결과:
{'오렌지', '사과', '바나나'}
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}
{1, 2, 3}
{1, 2, 3, 6, 7, 8}
{'오렌지', '사과', '바나나', '키위'}
{'오렌지', '사과', '키위'}
5. 스택과 큐 구현하기
파이썬의 리스트를 사용하여 스택과 큐를 구현할 수 있습니다.
# 스택 구현 (LIFO: Last In, First Out)
stack = []
# 요소 추가 (push)
stack.append(1)
stack.append(2)
stack.append(3)
print(f"스택: {stack}")
# 요소 제거 (pop)
top_item = stack.pop()
print(f"제거된 요소: {top_item}")
print(f"스택: {stack}")
# 큐 구현 (FIFO: First In, First Out)
from collections import deque
queue = deque()
# 요소 추가 (enqueue)
queue.append('A')
queue.append('B')
queue.append('C')
print(f"큐: {queue}")
# 요소 제거 (dequeue)
first_item = queue.popleft()
print(f"제거된 요소: {first_item}")
print(f"큐: {queue}")
출력 결과:
스택: [1][2][3]
제거된 요소: 3
스택: [1][2]
큐: deque(['A', 'B', 'C'])
제거된 요소: A
큐: deque(['B', 'C'])
6. 컴프리헨션(Comprehension)
컴프리헨션은 간결하게 리스트, 딕셔너리, 집합을 생성하는 방법입니다.
# 리스트 컴프리헨션
squares = [x**2 for x in range(1, 11)]
print(squares)
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares)
# 딕셔너리 컴프리헨션
square_dict = {x: x**2 for x in range(1, 6)}
print(square_dict)
# 집합 컴프리헨션
square_set = {x**2 for x in range(1, 11)}
print(square_set)
출력 결과:
[1][4][9][16][25][36][49][64][81][100]
[4][16][36][64][100]
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{64, 1, 4, 36, 100, 9, 16, 49, 81, 25}
7. collections 모듈의 특수 자료구조
파이썬의 collections 모듈은 추가적인 자료구조를 제공합니다.
from collections import Counter, defaultdict, OrderedDict, namedtuple
# Counter: 요소의 개수를 세는 딕셔너리
words = ['사과', '바나나', '사과', '오렌지', '바나나', '사과']
word_counts = Counter(words)
print(word_counts)
print(word_counts['사과'])
print(word_counts.most_common(2)) # 가장 많이 등장한 2개 요소
# defaultdict: 기본값이 있는 딕셔너리
fruit_colors = defaultdict(list)
fruit_colors['사과'].append('빨강')
fruit_colors['사과'].append('초록')
fruit_colors['바나나'].append('노랑')
print(dict(fruit_colors))
print(fruit_colors['오렌지']) # 키가 없어도 기본값 반환
# namedtuple: 이름 있는 필드를 가진 튜플
Person = namedtuple('Person', ['name', 'age', 'city'])
person = Person('홍길동', 30, '서울')
print(person)
print(person.name)
print(person.age)
print(person.city)
출력 결과:
Counter({'사과': 3, '바나나': 2, '오렌지': 1})
3
[('사과', 3), ('바나나', 2)]
{'사과': ['빨강', '초록'], '바나나': ['노랑']}
[]
Person(name='홍길동', age=30, city='서울')
홍길동
30
서울
정리
파이썬의 자료 구조는 다양한 문제를 해결하는 데 필요한 도구를 제공합니다. 각 자료 구조의 특성과 장단점을 이해하고 적절한 상황에서 활용하는 것이 중요합니다.
728x90
반응형
'개발 언어 > Python' 카테고리의 다른 글
PyUIBuilder: Python GUI 개발의 혁신적인 도구 (8) | 2025.05.23 |
---|---|
2025년 파이썬 초보자를 위한 무료 강의 추천 TOP 5 (4) | 2025.05.22 |
실시간 객체 인식 시스템: 웹캠과 모바일 카메라를 활용한 AI 기술 구현하기 (3) | 2025.05.11 |
파이썬 프로토콜 연동, 샘플 프로젝트로 쉽게 시작하기 (0) | 2025.05.11 |
Sentry를 사용하여 Django 프로젝트에서 Python 예외 처리 (0) | 2025.05.09 |