1. 튜플
1)특징
- 소괄호로 생성
- 값의 불변성: 데이터 무결성 유지
- 속도: 불변성으로 인해 리스트보다 빠르게 동작
- 메모리 효율성: 리스트보다 메모리를 적게 사용
+ .__add__()를 사용하면 값이 추가되는 것처럼 보이지만 실제로는 새로운 튜플이 생성된다.
2. 딕셔너리
1)특징
- key:value로 구성
- 중괄호 사용
- 변경 가능
- 순서 없음
- 키의 고유성: 같은 키 여러 번 사용시 마지막 값 저장
2) 사용 함수
생성 및 출력
키 목록: keys()
Colors.keys()
dict_keys(['Sam', 'Amy', 'Sarah'])
반복문 응용
for Item in Colors.keys():
print("{0} likes the color {1}."
.format(Item, Colors[Item]))
Sam likes the color Blue.
Amy likes the color Red.
Sarah likes the color Yellow.
삭제: del 튜플[키]
del Colors["Sam"]
3)딕셔너리를 응용해서 스위치문처럼 쓰기
(1)각 상황에 사용할 함수 생성
def PrintBlue():
print("You chose blue!\r\n")
def PrintRed():
print("You chose red!\r\n")
def PrintOrange():
print("You chose orange!\r\n")
def PrintYellow():
print("You chose yellow!\r\n")
(2) 딕셔너리 만들기
ColorSelect = {
0: PrintBlue,
1: PrintRed,
2: PrintOrange,
3: PrintYellow
}
(3)while문 작성
Selection = 0
while(Selection != 4):
print("0. Blue")
print("1. Red")
print("2. Orange")
print("3. Yellow")
print("4. Quit")
Selection = int(input("Select a color option: "))
if(Selection >= 0) and (Selection < 4):
ColorSelect[Selection]()
3. 스택
파이썬에서는 스택을 직접 제공하지 않지만 리스트와 컬렉션 모듈의 deque를 사용해서 구현할 수 있다.
1)리스트를 이용한 구현
MyStack = []
StackSize = 3
def DisplayStack():
print("Stack currently contains:")
for Item in MyStack:
print(Item)
def Push(Value):
if len(MyStack) < StackSize:
MyStack.append(Value)
else:
print("Stack is full!")
def Pop():
if len(MyStack) > 0:
MyStack.pop()
else:
print("Stack is empty.")
실행
Push(1)
Push(2)
Push(3)
DisplayStack()
input("Press any key when ready...")
Push(4)
DisplayStack()
input("Press any key when ready...")
Pop()
DisplayStack()
input("Press any key when ready...")
Pop()
Pop()
Pop()
DisplayStack()
4. 큐
1)특징
- 선입선출
- collections.deque 혹은 queue.Queue 모듈 사용
import queue
# 크기가 3인 큐 생성
MyQueue = queue.Queue(3)
# 큐가 비어 있는지 확인
print(MyQueue.empty()) # True, 큐가 비어 있음
# 사용자 입력 대기
input("Press any key when ready...")
# 큐에 데이터 추가
MyQueue.put(1)
MyQueue.put(2)
# 큐가 가득 찼는지 확인
print(MyQueue.full()) # False, 아직 큐에 여유 공간이 있음
# 사용자 입력 대기
input("Press any key when ready...")
# 큐에 데이터 추가
MyQueue.put(3)
# 큐가 가득 찼는지 확인
print(MyQueue.full()) # True, 큐가 가득 참
# 사용자 입력 대기
input("Press any key when ready...")
# 큐에서 데이터 제거
print(MyQueue.get()) # 1, 가장 먼저 들어간 데이터 제거
# 큐가 비어 있는지 확인
print(MyQueue.empty()) # False, 아직 데이터가 남아 있음
# 큐가 가득 찼는지 확인
print(MyQueue.full()) # False, 큐에 여유 공간이 생김
# 사용자 입력 대기
input("Press any key when ready...")
# 큐에서 데이터 제거
print(MyQueue.get()) # 2, 다음으로 들어간 데이터 제거
# 큐에서 데이터 제거
print(MyQueue.get()) # 3, 마지막으로 남은 데이터 제거
5. 데크
1)특징
- 양쪽 끝에서 삽입과 삭제를 할 수 있는 자료 구조
- collections 모듈의 deque 클래스를 사용해 구현
- 큐와 스택 두 가지의 특성을 모두 가짐
- 빠른 연산 속도: 시간 복잡도 O(1)
2)예제
import collections
# 데크 초기화
MyDeque = collections.deque("abcdef", 10)
print("Starting state:")
for Item in MyDeque:
print(Item, end=" ")
print("\r\n\r\nAppending and extending right")
# 오른쪽 끝에 요소 추가 및 확장
MyDeque.append("h")
MyDeque.extend("ij")
for Item in MyDeque:
print(Item, end=" ")
print("\r\nMyDeque contains {0} items.".format(len(MyDeque)))
print("\r\nPopping right")
print("Popping {0}".format(MyDeque.pop()))
for Item in MyDeque:
print(Item, end=" ")
print("\r\n\r\nAppending and extending left")
# 왼쪽 끝에 요소 추가 및 확장
MyDeque.appendleft("a")
MyDeque.extendleft("bc")
for Item in MyDeque:
print(Item, end=" ")
print("\r\nMyDeque contains {0} items.".format(len(MyDeque)))
print("\r\nPopping left")
print("Popping {0}".format(MyDeque.popleft()))
for Item in MyDeque:
print(Item, end=" ")
print("\r\n\r\nRemoving")
MyDeque.remove("a")
for Item in MyDeque:
print(Item, end=" ")
'Python > 기초' 카테고리의 다른 글
파이썬 기초⑦ 클래스 (0) | 2024.06.20 |
---|---|
파이썬 기초⑤ 리스트 다루기 (0) | 2024.06.18 |
파이썬 기초④ 문자열 다루기 (0) | 2024.06.17 |
파이썬 기초③ (0) | 2024.06.13 |
파이썬 기초② (0) | 2024.06.13 |