상세 컨텐츠

본문 제목

Module - collections

Python

by techbard 2024. 12. 3. 08:46

본문

반응형

 

# collections.defaultdict
# =======================
# A dictionary that returns a default value if the key has
# not been set yet.
# Simplifies code when dealing with missing dictionary keys

from collections import defaultdict

dd = defaultdict(int) # Default value is 0
print(dd)

dd['apple'] = 1 # Output: 1
dd['banana'] += 2 # Output: 2
print(dd)

print(dd['orange']) # Output: 0 (default value)

# 결과
defaultdict(<class 'int'>, {})
defaultdict(<class 'int'>, {'apple': 1, 'banana': 2})
0

 

# collections.OrderedDict
# =======================
# A dictionary that maintains the order of keys as They
# are inserted.
# Useful when the order of items is important and needs to
# be preserved.

from collections import OrderedDict

od = OrderedDict()
od['apple'] = 1
od['banana'] = 2
od['cherry'] = 3

odd = OrderedDict()
odd['cherry'] = 1
odd['banana'] = 2
odd['apple'] = 3

print(f"{od=}") # 추가한 순서를 유지한다.
print(f"{odd=}") # 추가한 순서를 유지한다.

# 결과
od=OrderedDict({'apple': 1, 'banana': 2, 'cherry': 3})
odd=OrderedDict({'cherry': 1, 'banana': 2, 'apple': 3})

 

# 컬렉션 모듈의 사용
# Counter: 요소는 키, 요소의 수는 값으로 저장
from collections import Counter

my_list:list[int] = [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4]

d = {}
for k in my_list:
    if k in d:
        d[k] += 1
    else:
        d[k] = 1
print(d)

result = Counter(my_list) # Counter 객체를 리턴
print(dict(result))

string_count = Counter('helloworld!')
print(dict(string_count))

sentence = "How many times does each word show up in this sentence with a word"
words_count = Counter(sentence.split())
print(dict(words_count))

letters = 'aaaaabbbbbbcdddeeff'
c = Counter(letters)
most_common_letters = c.most_common(3)
print(most_common_letters)

# 결과
{1: 5, 2: 3, 3: 2, 4: 1}
{1: 5, 2: 3, 3: 2, 4: 1}
{'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1, '!': 1}
{'How': 1, 'many': 1, 'times': 1, 'does': 1, 'each': 1, 'word': 2, 'show': 1, 'up': 1, 'in': 1, 'this': 1, 'sentence': 1, 'with': 1, 'a': 1}
[('b', 6), ('a', 5), ('d', 3)]

 

# collections.Counter
# ===================
# A subclass of dict for counting hashable objects.
# Useful for tallying counts of items and finding the
# most common items.

from collections import Counter

c = Counter(['apple', 'banana', 'apple', 'orange', 'banana'])
print(c) # Output: Counter({'apple': 2, 'banana': 2, 'orange': 1})
print(c.most_common(2)) # Output: [('apple', 2), ('banana', 2)]

 

# collections.deque
# =================
# A double-ended queue that supports adding and
# removing elements from either end.
#
# Useful for implementing queues, stacks, and
# other data structures that require fast appends
# and pops from both ends.

from collections import deque

dq = deque([1, 2, 3])
dq.append(4) # Add to the right end
dq.appendleft(0) # Add to the left end

print(dq) # Output: deque([0, 1, 2, 3, 4])
print(dq.pop()) # Output: 4
print(dq.popleft()) # Output: 0

# 결과
deque([0, 1, 2, 3, 4])
4
0

 

from collections import namedtuple

Dog = namedtuple('Dog', ['age', 'breed', 'name'])
sammy = Dog(age=5, breed='Husky', name='Sam')
print(type(sammy))
print(sammy)

print(sammy.name)
print(sammy[0])
print(sammy[1])
print(sammy[2])

# index로 얻을 수도 있지만 큰 tuple의 경우 어떤 인덱스가
# 어떤 값인지 알기 어렵다. 물론 0-index는 유용할 수도 있다.
# 그런 경우 key로 얻는 것이 가능하다.
# 전체적인 형태는 class와 유사하다.

# 결과
<class '__main__.Dog'>
Dog(age=5, breed='Husky', name='Sam')
Sam
5
Husky
Sam
반응형

관련글 더보기

댓글 영역