ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

namedtuple

from collections import namedtuple


person_info = namedtuple("info", "name age address")
info = person_info("kim", 12, "111-11")
  • info.name, info.age, info.address์™€ ๊ฐ™์ด ์ ‘๊ทผ ํ•  ์ˆ˜ ์žˆ๋‹ค.
  • name, age, address๋ฅผ ์ธ๋ฑ์Šค 0 ~ 2(ex: info[0])๋กœ๋„ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค.

defaultdict

๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜๋‹ค ๋ณด๋ฉด, ์–ด๋–ค ํ‚ค์— ๋Œ€ํ•œ ๊ฐ’์ด ์—†๋Š” ๊ฒฝ์šฐ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค.

๋”•์…”๋„ˆ๋ฆฌ์— ๋Œ€ํ•œ ์ดˆ๊ธฐ๊ฐ’์„ ์ง€์ •ํ•˜๊ณ ์ž ํ•  ๋•Œ defualtdict์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

def cnt_word(words):
    cnt = {}
    for word in words:
        if word not in cnt:
            cnt[word] = 0
        cnt[word] += 1
    return cnt
  • ์œ„์˜ ์ฝ”๋“œ๋Š” ๋”•์…”๋„ˆ๋ฆฌ์— ํ•ด๋‹น word๊ฐ€ ์—†์œผ๋ฉด 0์œผ๋กœ ์ดˆ๊ธฐํ™” ํ•ด์ฃผ๊ณ , ์•„๋‹ ๊ฒฝ์šฐ +1์„ ํ•˜์—ฌ ์นด์šดํŠธ ํ•œ๋‹ค.
from collections import defaultdict


def cnt_word(words):
    cnt = defaultdict(int)
    for word in words:
        cnt[word] += 1
    return cnt
  • int()์˜ ๋ฐ˜ํ™˜ ๊ฐ’์€ 0 ์ด๋ฏ€๋กœ, ๋”•์…”๋„ˆ๋ฆฌ์˜ ์ดˆ๊ธฐ ๊ฐ’์€ 0์œผ๋กœ ์„ค์ •๋œ๋‹ค.
  • ๋”ฐ๋ผ์„œ ์œ„์™€ ๊ฐ™์ด if ๋ฌธ์„ ํ†ตํ•ด ์ดˆ๊ธฐํ™” ๊ณผ์ •์„ ์ง„ํ–‰ํ•˜์ง€ ์•Š์•„๋„ ๋œ๋‹ค.

deque

์Šคํƒ๊ณผ ํ์˜ ๊ธฐ๋Šฅ์„ ๋ชจ๋‘ ๊ฐ€์ง„ ๊ฐ์ฒด๋กœ ์‚ฌ์šฉํ•˜๋Š” ๋ฉ”์„œ๋“œ์— ๋”ฐ๋ผ ๊ธฐ๋Šฅ์„ ๋‹ฌ๋ฆฌ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

from collections import deque

# stack๋กœ ์‚ฌ์šฉ
# ์ž…/์ถœ๋ ฅ ์šฐ
# FIFO
dq = deque('1234')
dq.append('5')
dq.pop()

# queue๋กœ ์‚ฌ์šฉ
# ์ž…๋ ฅ ์šฐ, ์ถœ๋ ฅ ์ขŒ
# LIFO
dq.append('5')
dq.popleft()
  • ๊ฐ’์„ ์ถ”๊ฐ€ํ•˜๊ฑฐ๋‚˜ ์‚ญ์ œํ•  ๋•Œ, append, pop์„ ์‚ฌ์šฉํ•˜๋ฉด ์Šคํƒ ์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ๊ฐ’์„ ์ถ”๊ฐ€ํ•˜๊ฑฐ๋‚˜ ์‚ญ์ œํ•  ๋•Œ, append, leftpop์„ ์‚ฌ์šฉํ•˜๋ฉด ํ ์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

Counter

๋ฆฌ์ŠคํŠธ๋‚˜ ์ŠคํŠธ๋ง์—์„œ์˜ ๊ฐ ์›์†Œ๋“ค์„ ์นด์šดํŠธํ•  ๋•Œ ์œ ์šฉํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

from collections import Counter


nums = [1, 3, 5, 9, 1, 2, 3, 5, 12, 15, 19, 5]
# count๊ฐ€ ๋†’์€ ์ˆ˜ ๋ถ€ํ„ฐ ๋”•์…”๋„ˆ๋ฆฌ๋กœ ๋ฐ˜ํ™˜๋จ
print(Counter(nums).most_common())
# count๊ฐ€ ๊ฐ€์žฅ ๋†’์€ ์ˆ˜๋งŒ ์ถœ๋ ฅ
print(Counter(nums).most_common(1))
  • Counter์˜ ๊ฒฝ์šฐ ๋”•์…”๋„ˆ๋ฆฌ์˜ ํ™•์žฅ์ด๊ธฐ์—, ๋”•์…”๋„ˆ๋ฆฌ์— ์‚ฌ์šฉํ•˜๋Š” ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ๋งŒ์•ฝ Counter์—์„œ ์ตœ๋Œ€ ๊ฐ’์˜ ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ ์ž ํ•œ๋‹ค๋ฉด Counter(nums).most_common()[0][1]๋กœ ์‚ฌ์šฉํ•œ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€