[Python] Collection Module

Suyeon·2021년 9월 23일
0

Python

목록 보기
2/3
post-thumbnail

The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them.
(본 글은 GeeksforGeeks을 참고하여 작성하였습니다.)

Counter

A counter is a sub-class of the dictionary. It is used to keep the count of the elements in an iterable in the form of an unordered dictionary.

예제1)

from collections import Counter

c = Counter('gallahad') # string  
c = Counter(['B','B','A','B','C','A','B']) # list 
c = Counter({'red': 4, 'blue': 2}) # dictionary   
c = Counter(cats=4, dogs=8) # keyword args

예제2)

a = 'aaaabbc'
counter = Counter(a)

print(counter)  # Counter({'a': 4, 'b': 2, 'c': 1})
print(counter.items())  # dict_items([('a', 4), ('b', 2), ('c', 1)])
print(counter.keys())  # dict_keys(['a', 'b', 'c'])
print(counter.values())  # dict_values([4, 2, 1])
print(counter.most_common(1)[0][0])  # 'a'
print(list(counter.elements()))  # ['a', 'a', 'a', 'a', 'b', 'b', 'c']

OrderedDict

An OrderedDict is also a sub-class of dictionary but unlike dictionary, it remembers the order in which the keys were inserted.

  • orderedDict([list])
d = OrderedDict([('a', 1), ('b', 2)])

d.update({'c': 3})
print(d.popitem(last = True)) # pop last item
print(d.popitem(last = False)) # pop first item
d.move_to_end('b',last=True) # move to last
d.move_to_end('b',last=False) # move to first

DefaultDict

  • int, list등을 default값으로 설정할 수 있다.
# defaultDict를 사용하지 않은 경우
def letterCounter(word):
    counter = {}
    for letter in word:
        counter.setdefault(letter, 0)
        counter[letter] += 1
    return counter
    
# defaultDict
def letterCounter(word):
    counter = defaultdict(int)
    for letter in word:
        counter[letter] += 1
    return counter

NamedTuple

namedtuple(typename, field_names)

Student = namedtuple('Student', ['name', 'age', 'DOB'])
s = Student('Suyeon', '23', '2541997')

print(s) # Student(name='Suyeon', age='23', DOB='2541997')
print(s[0]) # access using index
print(s.name) # access using key

Deque

Deque (Doubly Ended Queue) is the optimized list for quicker append and pop operations from both sides of the container. It provides O(1) time complexity for append and pop operations. (list has O(n) time complexity)

queue = deque([1, 2, 3])

queue.append(4)  # insert to right
queue.appendleft(0)  # insert to left
queue.pop()  # delete from right
queue.popleft()  # delete from left
profile
Hello World.

0개의 댓글