[부스트캠프 AI Tech 5기] Pre-Course : (1) Python Data Structure

araseo·2022년 12월 5일
0
post-thumbnail

📖 파이썬 기본 데이터 구조

  • 스택과 큐(stack & queue with list)
  • 튜플과 집합(tuple & set)
  • 사전(dictionary)
  • Collection 모듈

📖 문자열(string)

  • 시퀀스 자료형으로 문자형 data를 메모리에 저장
  • 영문자 한 글자는 1byte의 메모리공간을 사용

📖 스택(stack)

  • 나중에 넣은 데이터를 먼저 반환하도록 설계된 메모리 구조
  • Last In First Out (LIFO)
  • Data의 입력을 Push, 출력을 Pop이라고 함

📖 스택 (stack) with list object

  • 리스트를 사용하여 스택 구조를 구현 가능
  • push를 할 때는 append(), pop을 할 때는 pop()을 사용
>>> a = [1,2,3,4,5]
>>> a.append(10)
>>> a.append(20)
>>> a.pop() # 20 출력
20
>>> a.pop() # 10 출력
10

📖 stack example

  • 스택 구조를 활용, 입력된 글자를 역순으로 출력
word = input("Input a word : ") # Input Word
word_list = list(word)			# String to List
for i in range(len(word_list)):
	print(word_list.pop())		# 하나씩 빼면서 출력

📖 큐 (Queue)

  • 먼저 넣은 데이터를 먼저 반환하도록 설계된 메모리 구조
  • First In First Out (FIFO)
  • Stack과 반대되는 개념

📖 큐 (Queue) with list object

  • 파이썬은 리스트를 사용하여 큐 구조를 활용
  • put을 할 때는 append()를, get을 할 때는 pop(0)를 사용
>>> a = [1,2,3,4,5]
>>> a.append(10)
>>> a.append(20)
>>> a.pop(0) # 1 출력
1
>>> a.pop(0) # 2 출력
2

📖 튜플(tuple)

  • 값의 변경이 불가능한 리스트
  • 선언 시 []가 아닌 ()를 사용
  • 리스트의 연산, 인덱싱, 슬라이싱 등을 동일하게 사용
>>> t = (1,2,3)
>>> print(t+t, t*2) # (1, 2, 3, 1, 2, 3) (1, 2, 3, 1, 2, 3)
>>> len(t)
3
>>> t[1] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
 TypeError: 'tuple' object does not support item assignment
  • 왜 쓸까?
    • 프로그램을 작동하는 동안 변경되지 않은 데이터의 저장
      Ex) 학번, 이름, 우편번호 등등
    • 함수의 반환 값등 사용자의 실수에 의한 에러를 사전에 방지
>>> t = (1) # 일반 정수로 인식
1
>>> t = (1, ) # 값이 하나인 Tuple은 반드시 "," 를 붙여야 함
(1, )

📖 집합 (set)

  • 값을 순서없이 저장, 중복 불허하는 자료형
  • set 객체 선언을 이용하여 객체 생성
>>> s = set([1,2,3,1,2,3,]) # set 함수를 사용하여 [1,2,3,1,2,3]을 집합 객체로 생성, a = {1,2,3,1,2,3} 도 가능
>>> s
{1,2,3}
>>> s.add(1) 				# 중복 불허로 1은 추가 되지 않음
>>> s
{1,2,3}
>>> s.remove(1) # 1 삭제
>>> s
{2,3}
>>> s.update([1,4,5,6,7]) 	# [1,4,5,6,7] 추가
>>> s
{1,2,3,4,5,6,7}
>>> s.discard(3) 			# 3 삭제
>>> s
{1,2,4,5,6,7}
>>> s.clear() 				# 모든 원소 삭제
  • 수학에서 활용하는 다양한 집합연산 가능
>>> s1 = set([1,2,3,4,5])
>>> s2 = set([3,4,5,6,7])
>>> s1.union(s2) 		# s1 과 s2의 합집합
{1, 2, 3, 4, 5, 6, 7}
>>> s1 | s2
{1, 2, 3, 4, 5, 6, 7}
>>> s1.intersection(s2) # s1 과 s2의 교집합
{3, 4, 5}
>>> s1 & s2
{3, 4, 5}
>>> s1.difference(s2) 	# s1 과 s2의 차집합
{1, 2}
>>> s1 - s2
{1, 2}

📖 사전 (dictionary)

  • 데이터를 저장할 때는 구분 지을 수 있는 값을 함께 저장
    예) 주민등록번호, 제품 모델 번호
  • 구분을 위한 데이터 고유값을 Identifier 또는 Key 라고함
  • Key 값을 활용하여, 데이터 값(Value)를 관리함
  • Key와 Value를 매칭하여 Key로 Value를 검색
  • 다른 언어에서는 Hash Table 이라는 용어를 사용
  • {Key1:Value1, Key2:Value2, Key3:Value3 ...} 형태
student_info = {20140012:'Sungchul', 20140059:'Jiyong', 20140058:'JaeHong'}

student_info[20140012] = 'Janhyeok'
student_info[20140039] = 'Wonchul'
keyValue
20140012Janhyeok
20140059Jiyong
20140058JaeHong
20140039Wonchul

📖 사전 (dictionary) 다루기

>>> country_code = {} # Dict 생성, country_code = dict() 도 가능
>>> country_code = {"America": 1, "Korea": 82, "China": 86, "Japan": 81} >>> country_code
{'America': 1, 'China': 86, 'Korea': 82, 'Japan': 81}
>>> country_code.items() # Dict 데이터 출력
Dict_items([('America', 1), ('China', 86), ('Korea', 82), ('Japan', 81)])
>>> country_code.keys() # Dict 키 값만 출력
Dict_keys(["America", "China", "Korea", "Japan"])
>>> country_code["German"]= 49 # Dict 추가
>>> country_code
{'America': 1, 'German': 49, 'China': 86, 'Korea': 82, 'Japan': 81}
>>> country_code.values() # Dict Value만 출력
dict_values([1, 49, 86, 82, 81])
>>> for k,v in country_code.items():
... print ("Key : ", k)
... print ("Value : ", v) ...
Key : America
Value : 1
Key : Gernman
Value : 49
Key : China
Value : 86
Key : Korea
Value : 82
Key : Japan
Value : 81
>>> "Korea" in country_code.keys() # Key값에 "Korea"가 있는지 확인 True
>>> 82 in country_code.values() # Value값에 82가 있는지 확인 True

📖 collections

  • List, Tuple, Dict에 대한 Python Built-in 확장 자료 구조(모듈)
  • 편의성, 실행 효율 등을 사용자에게 제공함
  • 아래의 모듈이 존재함
from collections import deque
from collections import Counter
from collections import OrderedDict
from collections import defaultdict
from collections import namedtuple

📖 deque

  • Stack과 Queue를 지원하는 모듈
  • List에 비해 효율적인(=빠른) 자료 저장 방식을 지원함
from collections import deque
deque_list = deque()
for i in range(5):
	deque_list.append(i)
print(deque_list)
deque_list.appendleft(10) print(deque_list)
  • rotate, reverse 등 Linked List의 특성을 지원함
  • 기존 list 형태의 함수를 모두 지원함

deque_list.rotate(2)
print(deque_list)
deque_list.rotate(2)
print(deque_list)
print(deque(reversed(deque_list)))
deque_list.extend([5, 6, 7])
print(deque_list)
deque_list.extendleft([5, 6, 7])
print(deque_list)
  • deque는 기존 list보다 효율적인 자료구조를 제공
  • 효율적 메모리 구조로 처리 속도 향상
# deque
from collections import deque
import time

start_time = time.clock()
deque_list = deque()

for i in range(10000):
    for i in range(10000):
        deque_list.append(i)
        deque_list.pop()
        
print(time.clock() - start_time, "seconds")

# general list
import time

general list
start_time = time.clock()
just_list = []

for i in range(10000):
    for i in range(10000):
        just_list.append(i)
        just_list.pop()
        
print(time.clock() - start_time, "seconds")

📖 OrderedDict

  • Dict와 달리, 데이터를 입력한 순서대로 dict를 반환함
  • 그러나 python 3.6부터 dict 자체에서도 입력한 순서를 보장하여 출력하기 시작함
  • Dict type의 값을, value 또는 key 값으로 정렬할 때 사용 가능
# key를 기준으로 정렬
for k, v in OrderedDict(sorted(d.items(), key=lambda t: t[0])).items():
	print(k, v)
    
# value를 기준으로 정렬
for k, v in OrderedDict(sorted(d.items(), key=lambda t: t[1])).items():
	print(k, v)

📖 defaultdict

  • Dict type의 값에 기본 값을 지정, 신규값 생성시 사용하는 방법
from collections import defaultdict
d = defaultdict(object) # Default dictionary를 생성
d = defaultdict(lambda: 0) # Default 값을 0으로 설정합 
print(d["first"])
text = """A press release is the quickest and easiest way to get free publicity. If well written, a press release can result in multiple published articles about your firm and its products. And that can mean new prospects contacting you asking you to sell to them. ....""".lower().split()

from collections import OrderedDict

word_count = defaultdict(lambda: 0) # Default 값을 0으로 설정합니다.

for word in text:
    word_count[word] += 1

# 단어가 나온 빈도수 순서대로 출력
for i, v in OrderedDict(sorted(
        word_count.items(), key=lambda t: t[1],
        reverse=True)).items():
    
    print(i, v)

📖 Counter

  • Sequence type의 data element들의 갯수를 dict 형태로 반환
from collections import Counter

c = counter()			# a new, empty counter
c = Counter('gallahad') # a new counter from an iterable
print(c)
Counter({'a': 3, 'l': 2, 'g': 1, 'd': 1, 'h': 1})
  • Dict type, keyword parameter 등도 모두 처리 가능
  • Set의 연산들을 지원함
  • word counter의 기능도 손쉽게 제공함

📖 namedtuple

  • Tuple 형태로 Data 구조체를 저장하는 방법
  • 저장되는 data의 variable을 사전에 지정해서 저장함
from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)
print(p[0] + p[1])

x, y = p
print(x, y)
print(p.x + p.y)
print(Point(x=11, y=22))

<이 게시물은 최성철 교수님의 Python Data Structure 강의 자료를 참고하여 작성되었습니다.>

본 포스트의 학습 내용은 [부스트캠프 AI Tech 5기] Pre-Course 강의 내용을 바탕으로 작성되었습니다.
부스트캠프 AI Tech 5기 Pre-Course는 일정 기간 동안에만 운영되는 강의이며,
AI 관련 강의를 학습하고자 하시는 분들은 부스트코스 AI 강좌에서 기간 제한 없이 학습하실 수 있습니다.
(https://www.boostcourse.org/)

profile
AI를 공부하고 있는 학생입니다:)

0개의 댓글