📖 파이썬 기본 데이터 구조
📖 문자열(string)
📖 스택(stack)
📖 스택 (stack) with list object
>>> 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)
📖 큐 (Queue) with list object
>>> 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
>>> t = (1) # 일반 정수로 인식
1
>>> t = (1, ) # 값이 하나인 Tuple은 반드시 "," 를 붙여야 함
(1, )
📖 집합 (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)
student_info = {20140012:'Sungchul', 20140059:'Jiyong', 20140058:'JaeHong'}
student_info[20140012] = 'Janhyeok'
student_info[20140039] = 'Wonchul'
key | Value |
---|---|
20140012 | Janhyeok |
20140059 | Jiyong |
20140058 | JaeHong |
20140039 | Wonchul |
📖 사전 (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
from collections import deque
from collections import Counter
from collections import OrderedDict
from collections import defaultdict
from collections import namedtuple
📖 deque
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)
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
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
# 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
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
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})
📖 namedtuple
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/)