본문 바로가기
Python

데이터 구조

by YUNZEE 2024. 7. 2.
728x90
데이터 구조 생각해보기

- 전화번호부 정보는 어떻게 저장하면 좋을까?

- 서적 정보는 어떻게 관리하면 좋을까?

- 창고에 쌓인 수화물의 위치를 역순으로 찾을 때?

 

스택과 큐(stack & queue with list)

스택(stack)

- 나중에 넣은 데이터를 먼저 반환

- Last In First Out(LIFO)

- Data의 입력을 Push, 출력을 Pop이라고 

- 스택 구조를 활용, 입력된 글자를 역순으로 출력

word = input("Input a word: ")
word_list = list(word)
for i in range(len(word_list)):
    print(word_list.pop()) #하나씩 빼면서 출력
#결과: 맨 마지막인 r부터 빠짐
Input a word: naver
r
e
v
a
n

 

큐 (Queue)

- 먼저 넣은 데이터를 반환

- First In First Out (FIFO)

- 파이썬은 리스트를 사용하여 큐 구조를 활용

- put를 append( ), get을 pop(0)를 사용

#Queue
a = [1,2,3,4,5]
a.append(7) #뒤에 7추가
a.pop(2) #3 빠짐
print(a) #결과: [1, 2, 4, 5, 7]
튜플과 집합(tuple & set)

튜플(tuple)

- 값이 변경이 불가능한 리스트

- 선언 시 "[ ]"가 아닌 "( )"를 사용

- 리스트의 연산, 인덱싱, 슬라이싱 등을 동일하게 사용

 

사용하는 이유

- 프로그램을 작동하는 동안 변화면 안 되는 데이터에 사용

ex) 학번, 이름, 우편번호

#tuple
t = (1,2,3)
print(t+t)
print(t*2)
print(len(t))# t의 값이 개수가 바뀌지 않음
# 결과
(1, 2, 3, 1, 2, 3)
(1, 2, 3, 1, 2, 3)
3

 

집합(set)

- 값을 순서 없이 저장, 중복 불허 하는 자료형

- set 객체 선언을 이용하여 객체 생성

 

jupyter tip

Esc + a 셀 삽입

dd 셀 삭제

#set
s = set([1,2,3,4])
s.add(5) #{1, 2, 3, 4, 5}
s.remove(1) #{2, 3, 4, 5}
s.update([8,9]) #{2, 3, 4, 5, 8, 9}
s.discard(3) #{2, 4, 5, 8, 9}
s.clear() #set()
print(s)
s1 = set([1,2,3,4])
s2 = set([4,5,6,7])
s1|s2 #결과: {1, 2, 3, 4, 5, 6, 7}
s1.union(s2) #결과: {1, 2, 3, 4, 5, 6, 7}
s1 & s2 #결과: {4}
s1.difference(s2)#결과: {1, 2, 3}
s1 - s2#결과: {1, 2, 3}
사전(dictionary)

- 데이터를 저장할 때는 구분 지을 수 있는 값을 함께 저장

- 구분을 위한 데이터 고유 값을 Identifier 또는 Key라고 함

- Key값을 활용하여, 데이터 값(Value)을 관리함

code = {"a": 1, "b":2, "c":3}
code.items() #dict_items([('a', 1), ('b', 2), ('c', 3)])
code.keys() #dict_keys(['a', 'b', 'c'])
code["a"] = 55 #{'a': 55, 'b': 2, 'c': 3}
code.values() #dict_values([55, 2, 3])
for k,v in code.items():
    print("key: ",k)
    print("value: ", v)
#결과
key:  a
value:  55
key:  b
value:  2
key:  c
value:  3
"a" in code.keys() #True
Collection 모듈

 defaultdict

- Dict type의 값에 기본 값을 지정, 신규값 생성 시 사용하는 방법

from collections import defaultdict
d = defaultdict(object) #Default dictionary를 생성
d = defaultdict(lambda: 0) #Default값을 0으로 설정
print(d["first"]) #결과: 0

 

Counter

- set의 확장형

- Sequence type의 data element들의 개수를 dict형태로 반환

from collections import Counter
c = Counter()
c = Counter('gallahad')
print(c)
#결과: Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})
a = Counter(a=1, b=2, c=3)
b = Counter(a=1, b=2, c=3, d=-2)
print(a+b)
print(a&b)
print(a|b)
#결과
Counter({'c': 6, 'b': 4, 'a': 2})
Counter({'c': 3, 'b': 2, 'a': 1})
Counter({'c': 3, 'b': 2, 'a': 1})

namedtuple

- 데이터를 구조체를 하나로 묶을 수 있다?

- Tuple형태로 Data 구조체를 저장하는 방법

- 저장되는 data의 variable을 사전에 지정해서 저장

from collections import namedtuple
Point = namedtuple('point', ['x','y'])
p = Point(11, y=22)
print(p[0]+p[1]) #33
print(x,y) # 11 33
print(p.x + p.y) #33

 

728x90