카테고리 없음
[부캠] Python Data Structure
리하이
2021. 1. 20. 23:07
- 스택(Stack)
- 큐(Queue)
- 튜플(Tuple)
- 집합(Set)
- 사전(dictionary)
- Collection 모듈
스택(Stack)
-Last In Last Out 의 메모리 구조
-주로 리스트를 이용해서 스택을 구현함.
a=[1,2,3,4,5]
a.append(6) #stack에 push
a.append(7)
a.pop() #stack에서 pop
큐(Queue)
- FIFO(First In First Out) 의 구조
- 리스트 또는 collection deque 모듈을 사용하여 구현
a=[1,2,3,4,5]
a.append(6) #push
a.pop(0) #제일 처음인 원소를 반환
from collections import deque
a=deque()
a.append(1)
a.append(2)
a.popleft()
튜플(Tuple)
-값의 변경이 불가능한 리스트
- () 를 사용하여 선언
- 프로그램을 작동하는 동안 변경되지 않는 데이터의 저장에 이용
t=(1,2,3)
집합(Set)
-값의 순서없이 저장
-중복 불허하는 자료형
-수학의 다양한 집합연산 가능
s=set([1,2,3,4])
s.add(1) # 중복안됨
#s={1,2,3,4}
s.remove(1)
#s={2,3,4}
s.clear()
#s={}
s1=set([1,2,3])
s2=set([2,3,4,5])
s1.union(s2) #합집합
#{1,2,3,4,5}
s1|s2 #합집합
#{1,2,3,4,5}
s1.intersection(s2) #교집합
#{2,3}
s1&&s2 #교집합
#{2,3}
s1.difference(s2) #차집합
#{1}
s1-s2 #차집합
#{1}
사전(Dictionary)
-Key값-Value값으로 저장되는 자료구조
-Hash Table이라는 용어로도 사용 (엄연히는 다름)
dict={'one':1,'two':2,'three':3}
dict['four']=4
#dict={'one':1,'two':2,'three':3,'four':4}
dict.keys()
#dict_keys(['one','two',three','four'])
dict.values()
#dict_values([1,2,3,4])
Collection module 모음
from collections import deque
from collections import Counter
from collections import defaultdict
from collections import namedtuple
#더 빠른 stack, queue를 만들 수 있음
from collections import deque
deque_list = deque()
for i in range(5):
deque_list.append(i)
deque_list.appendleft(10)
print(deque_list)
from collections import defaultdict
#d = defaultdict(object)
d = defaultdict(lambda: 0) # Default 값을 0으로 설정함
print(d["first"])
#0
from collections import Counter
s='abcdeffg'
sc=Counter(s)
#sc={'a':1,'b':2,'c':3,'d':1,'e':1,'f':2,'g':1}