[Python] Data Structure

Jeonghyunยท2022๋…„ 9์›” 20์ผ
0

Python ์ด๋ก 

๋ชฉ๋ก ๋ณด๊ธฐ
1/9
post-custom-banner

๐Ÿ“Œ ํŒŒ์ด์ฌ์˜ ๊ธฐ๋ณธ ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ

  • ์Šคํƒ๊ณผ ํ
  • ํŠœํ”Œ๊ณผ ์ง‘ํ•ฉ
  • ์‚ฌ์ „
  • Collection ๋ชจ๋“ˆ

์Šคํƒ (stack)

  • ๋‚˜์ค‘์— ๋„ฃ์€ ๋ฐ์ดํ„ฐ๋ฅผ ๋จผ์ € ๋ฐ˜ํ™˜
  • Last in First Out (LIFO)
  • Data์˜ ์ž…๋ ฅ์„ Push, ์ถœ๋ ฅ์„ Pop

๋ฆฌ์ŠคํŠธ๋กœ ๊ตฌํ˜„ ๊ฐ€๋Šฅ
Push๋Š” append(), Pop์€ pop()

ํ (queue)

  • ๋จผ์ € ๋„ฃ์€ ๋ฐ์ดํ„ฐ๋ฅผ ๋จผ์ € ๋ฐ˜ํ™˜
  • First in First Out (FIFO)
  • ์Šคํƒ๊ณผ ๋ฐ˜๋Œ€

Put์€ append(), get์€ pop(0)์„ ์‚ฌ์šฉ

ํŠœํ”Œ (tuple)

  • ์„ ์–ธ์‹œ '( )' ์‚ฌ์šฉ
  • ๋ฆฌ์ŠคํŠธ์™€ ๋™์ผํ•˜๊ฒŒ ์‚ฌ์šฉํ•˜์ง€๋งŒ ๊ฐ’์˜ ๋ณ€๊ฒฝ์ด ๋ถˆ๊ฐ€๋Šฅ
    ๐Ÿ‘‰ ์‚ฌ์šฉ์ž์˜ ์‹ค์ˆ˜์— ์˜ํ•œ ์—๋Ÿฌ๋ฅผ ์‚ฌ์ „ ๋ฐฉ์ง€

์ง‘ํ•ฉ (set)

  • ๊ฐ’์„ ์ˆœ์„œ์—†์ด ์ €์žฅ(์ค‘๋ณต ๋ถˆ๊ฐ€)
  • set() ์ด๋‚˜ { }๋กœ ์„ ์–ธ
  • ์ง‘ํ•ฉ ์—ฐ์‚ฐ (s1, s2)
    • ํ•ฉ์ง‘ํ•ฉ s1.union(s2) / s1 | s2
    • ๊ต์ง‘ํ•ฉ s1.intersection(s2) / s1 & s2
    • ์ฐจ์ง‘ํ•ฉ s1.differcence(s2) / s1 - s2

์‚ฌ์ „ (dictionary)

  • ๋ฐ์ดํ„ฐ๋ฅผ ๊ตฌ๋ถ„์„ ์œ„ํ•œ ๊ณ ์œ  ๊ฐ’(identifier, key)์™€ ํ•จ๊ป˜ ์ €์žฅ
  • Key ๊ฐ’๊ณผ ๋ฐ์ดํ„ฐ ๊ฐ’(Value)๋ฅผ ๊ด€๋ฆฌ
    {Key1:Value1, Key2:Value2, ...}์˜ ํ˜•ํƒœ

dict()๋‚˜ { }๋กœ ์ƒ์„ฑ

numbers = {"one" : 1, "two" : 2, "three" : 3} 
numbers.items()  ๐Ÿ‘‰  ๋ฐ์ดํ„ฐ ์ถœ๋ ฅ (ํŠœํ”Œ ํ˜•ํƒœ)
numbers.keys()   ๐Ÿ‘‰  ํ‚ค ๊ฐ’๋งŒ ์ถœ๋ ฅ
numbers.values()  ๐Ÿ‘‰ Value๋งŒ ์ถœ๋ ฅ
numbers["four"] = 4  ๐Ÿ‘‰ Dict ์ถ”๊ฐ€

collecions

  • 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

1. deque

  • ์Šคํƒ๊ณผ ํ ์ง€์›
  • ๋ฆฌ์ŠคํŠธ์— ๋น„ํ•ด ํšจ์œจ์ ์ด๊ณ  ๋น ๋ฆ„
  • linked list์˜ ํŠน์„ฑ
list.append() ๋ฐ์ดํ„ฐ ์ถ”๊ฐ€
list.appendleft() ๋ฐ์ดํ„ฐ ์™ผ์ชฝ์— ์ถ”๊ฐ€
list.rotate() ํ•œ์นธ์”ฉ ์ด๋™
list.extend() ์—ฌ๋Ÿฌ ๋ฐ์ดํ„ฐ ์ถ”๊ฐ€ 

2. OrderedDict

  • Dict์™€ ๋‹ฌ๋ฆฌ ๋ฐ์ดํ„ฐ๋ฅผ ์ž…๋ ฅํ•œ ์ˆœ์„œ๋Œ€๋กœ ๋ฐ˜ํ™˜ (์˜ˆ์ „ python์€ x) ๐Ÿ‘‰ ์ง€๊ธˆ์€ ์˜๋ฏธ ์—†์Œ

3. defaultdict

  • Dict type์˜ ๊ฐ’์— ๊ธฐ๋ณธ๊ฐ’์„ ์ง€์ •ํ•ด์คŒ
d = defaultdict(lambda : 0) ๐Ÿ‘‰ 0์œผ๋กœ ์ดˆ๊ธฐ๊ฐ’ ์„ค์ •

4. counter

  • sequence type์˜ data element๋“ค์˜ ๊ฐฏ์ˆ˜๋ฅผ dict ํ˜•ํƒœ๋กœ ๋ฐ˜ํ™˜
  • set์˜ ์—ฐ์‚ฐ ์ง€์›

5. namedtuple

  • ํŠœํ”Œ ํ˜•ํƒœ๋กœ Data ๊ตฌ์กฐ์ฒด ์ €์žฅ
  • variable์„ ์‚ฌ์ „ ์ง€์ •
{๊ตฌ์กฐ์ฒด} = namedtuple({๊ตฌ์กฐ์ฒด ์ด๋ฆ„}, [{๊ตฌ์กฐ์ฒด ๋ณ€์ˆ˜1}, {๊ตฌ์กฐ์ฒด ๋ณ€์ˆ˜2}])
Point = namedtuple('Point',['x', 'y'])
p = Point(x = 11, y = 22)
print(p.x + p.y)





[๋ถ€์ŠคํŠธ์บ ํ”„ AI Tech] Week 1 - Day 2

post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€