데이터 구조

이상해씨·2023년 4월 14일
0

AI 기초

목록 보기
14/15

자료구조

  1. 스택
  2. 튜플
  3. 집합
  4. 사전
  5. collection 모듈

1. stack

  • 나중에 넣은 데이터를 먼저 반환
  • LIFO 리포 구조
  • 입력 push, 출력 pop
  • list를 사용하여 구현
    - push를 append(), pop을 pop()을 사용하여 구현
    - pop은 return 있으면서 변환함수
  • 글자 역순 출력

2. Queue

  • 먼저 넣으면 먼저 반환
  • FIFO
  • stack과 반대
  • append(), pop(0)
  • list를 사용하여 활용

3. tuple

  • 값의 변경이 불가한 리스트

  • () 사용

  • 리스트의 슬라이싱, 인덱실, 연산은 가능하나, tuple 자체 값의 변화는 없음

  • 사용하는 이유?
    변경하면 안되는 데이터의 변환 방지, 실수에 의한 에러 방지.

    ```
    t=(1,2,3)
    t+t = (1,2,3,1,2,3)
    len(t)=3
    print(t) # (1,2,3)
    
    # 값의 변경이 불가 (할당 X)
    t[1] = 4 #Error
    ```
  • ()안에 ,를 기입해 주어야 튜플타입으로 인식이 됨.

t=(1) # 정수 타입
t=(1,) # 튜플타입

4. Set

  • 순서 없이 저장, 중복 불허
  • 집합
  • set([1,2,3])/ s={1,2,3}으로 선언

set 메소드

  • s.add(1)
  • s.remove(1)
  • s.update([1,2,3]) #한번에 여러개를 추가할 때 사용
  • s.discard(1) 삭제
  • s.clear() 모두 삭제

집합 연산

  • 합집합
    s1 | s2
    s1.union(s2)
  • 교집합
    s1 & s2
    s1.intersection(s2)
  • 차집합
    s1 - s2
    s1.difference(s2)

5.dictionary

  • 사전
  • 데이터 저장시 구분할 수 있는 데이터 값을 같이 저장
  • 데이터 고유값을 identifier, key라고 함
  • key를 이용하여 value 관리
  • {Key1:value1, Key2:value2, Key3:value3}로 생성
a=dict()
info ={"Apple":1, "banana":2, "kiwi":3}
info.items() # 데이터 출력
info.keys() #키 값만 룰력
info["Apple"]=53 #dict 추가
info.value()

for i in info.items():
	print(type(i))
    
for k,v in info.items():
	print("key":k)
    print("value":v)
    
    
"kiwi" in info.keys() # key값에 kiwi있는지 확인
53 in info.values()

6.collections

  • 리스트, 튜플, 사전에 대한 확장 모듈
  • 편의성,

6-1. collections 모듈종류

  1. from collections import deque
  2. from collections import Counter
  3. from collections import OrderedDict
  4. from collections import defaultdict
  5. from collections import namedtuple

1, deque

1) stack, queue를 지원

  • deque_list는 list 함수 지원
  • list에 비해 빠른 저장
from collections import deque

#deque_list =[1,2,3,4,5]
deque_list= deque()

deque_list.append(1)
#deque_list =[1,2,3,4,5,1]

deque_list.appendleft(10)
#deque_list =[10,1,2,3,4,5,1]


#deque_list.extend([1,2,3])
#deque_list =[10,1,2,3,4,5,1,[1,2,3]]

2) linked list 특성을 지원 list.rotate

  • linked list: 유연하게 시퀀스형 데이터를 표현할 수 있는 형태
  • 기존 리스트 함수를 지원 + linked list특성 (rotate, reverse)지원
# deque_list
deque_list= [1,2,3,4,5,6,7,8,9]
deque_list.rotate(2)
#deque_list =[8,9,1,2,3,4,5,6,7]


print(deque(reversed(deque_list)))


deque_extend([1,2,3])
deque_list.extendleft([1,2,3])
  • %timeit : 여러번 돌려서 편균시간을 반환해줌.

2. OrderedDict

  • 입력한 데이터 순서에 따라 dict 반환
  • 과거에는 dict이 입력 순서대로 반환하지 못하였으나, 현재 버전의 파이썬은 기능을 제공하여 ordereddict의 존재의미가 사라짐.

3. defualtDict

  • dict type 값에 기본 값 설정
  • defualtdict(인자) : 인자를 dictionary의 초깃값으로 지정
from collections import defualtdict
#defualt값을 0으로 설정,함수 형태로 넣어야 함/
d =defaultdict(lambda :0)
d["first"] # 0
d["seconde"]# 0
  • 단어 갯수 셀 때

4. Counter

  • 시퀀스 타입의 데이터 elemet 갯수를 dict 형태로 반환
  • element 갯수를 세주는 함수
from collections import Counter

c= Counter()
c= Counter('apple pie')
print(c) # Counter({'a':1, 'p':3, 'l':1,'e':2, 'i':1})
  • element를 dict으로 변환해주기도 함
c=Counter({'apple':3, 'banana':2})
print(list(c.elements())

c=Counter(cats=4, dogs=3)
print(list(c.elements())
#Counter ({'gods':3, 'cats':4})
#['gods','gods','gods','cats','cats','cats','cats']
  • 연산 기능
c=Counter(a=1,b=2,c=3,d=4)
d=Counter(a=1,b=1,c=2,d=2)
c.subtract(d)
print(c)
# Counter({'a':0, 'b':1,'c':1,'d':2})
print(c+d) 
print(c&d)
print(c|d)

5. namedtuple

  • tuple 형태에 data 구조체 저장
  • namedtuple('name',[''apple','banana'])
from collections import namedtuple

# English라 칭하고 그 안에 a와 b값이 있는 구조체 선언
Eng =namedtuple('English', ['a','b'])
# 이 구조체에 a값이 10, b값이 15가 들어간다. 
e=Eng(10 , b=15)

print(e[0]+e[1])
print(e.a+e.b)
  • 그러나, 파이썬에서는 class를 더 선호! (namedtuple을 잘 사용하지는 않음)

참고

profile
공부에는 끝이 없다

0개의 댓글