[Python] collection

Updated:

Python collection

문제λ₯Ό ν’€λ‹€ λͺ¨λ₯΄λŠ”κ²Œ μžˆμ–΄ collection 을 κ²€μƒ‰ν•΄λ΄€λŠ”λ° 이미 검색을 ν•΄λ³Έ κ°œλ…μ΄μ—ˆλ‹€..

κ·Έλž˜μ„œ 이제 λͺ¨λ₯΄λŠ”κ²Œ 생기고 검색을 ν•΄μ„œ μ•Œκ²Œλ˜λ©΄ κΌ­ 정리λ₯Ό ν•΄μ•Όκ² λ‹€κ³  마음 λ¨Ήμ—ˆλ‹€.

collection 은 μ—¬λŸ¬ μžλ£Œν˜•μ— μžˆλŠ” 데이터 개수λ₯Ό μ„Έμ–΄ dict ν˜•νƒœλ‘œ λ°˜ν™˜μ„ ν•΄μ£ΌλŠ” λͺ¨λ“ˆμ΄λ‹€.

list

import collections


_list = [1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 6, 6, 7]

print(collections.Counter(_list))
#  Counter({2: 4, 1: 2, 3: 2, 6: 2, 4: 1, 5: 1, 7: 1})

λ‹€μŒκ³Ό 같이 λ¦¬μŠ€νŠΈμ— μžˆλŠ” 데이터 개수λ₯Ό 세주기도 ν•˜κ³ 

str

import collections


_str = 'aabbbccdd111223'
print(collections.Counter(_str))
#  Counter({'b': 3, '1': 3, 'a': 2, 'c': 2, 'd': 2, '2': 2, '3': 1})

λ¬Έμžμ—΄μ— μžˆλŠ” 문자 κ°œμˆ˜λ„ μ„Έμ€€λ‹€.

dict

import collections


_dict = {'κ°€': 1, 'λ‚˜': 3, 'λ‹€': 2}
print(collections.Counter(_dict))
#  Counter({'λ‚˜': 3, 'λ‹€': 2, 'κ°€': 1})

dict λ₯Ό λ„£μœΌλ©΄ value 값이 큰 μˆœμ„œλŒ€λ‘œ 정렬을 ν•΄μ€€λ‹€.

λ‹€μ–‘ν•œ μ—°μ‚°

import collections


cnt_a = collections.Counter('aabbcc')
cnt_b = collections.Counter('ccddee')
print(cnt_a + cnt_b)  #  Counter({'c': 4, 'a': 2, 'b': 2, 'd': 2, 'e': 2})
print(cnt_a - cnt_b)  #  Counter({'a': 2, 'b': 2})
print(cnt_a & cnt_b)  #  Counter({'c': 2})
print(cnt_a | cnt_b)  #  Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2, 'e': 2})

λ‹€μ–‘ν•œ 연산도 κ°€λŠ₯ν•˜λ‹€. λΊ„μ…ˆμ˜ 경우 μŒμˆ˜κ°€ 생기면 좜λ ₯ν•˜μ§€ μ•ŠλŠ”λ‹€. cnt_a - cnt_b λ₯Ό ν–ˆκΈ° λ•Œλ¬Έμ— d, e λŠ” -2 κ°€ λ˜μ–΄ 좜λ ₯λ˜μ§€ μ•ŠλŠ”λ‹€.

ꡐ집합과 합집합도 연산이 κ°€λŠ₯ν•˜λ‹€.


import collections


cnt_a = collections.Counter('aabbcc')
cnt_b = collections.Counter('ccddee')
cnt_a.subtract(cnt_b)
print(cnt_a)  #  Counter({'a': 2, 'b': 2, 'c': 0, 'd': -2, 'e': -2})

μ•žμ„œ λΊ„μ…ˆμ˜ 경우 μŒμˆ˜κ°€ 생기면 좜λ ₯ν•˜μ§€ μ•Šμ§€λ§Œ subtract λ₯Ό μ‚¬μš©ν•˜λ©΄ 음수 값도 좜λ ₯이 κ°€λŠ₯ν•˜λ‹€.


Categories:

Updated:

Leave a comment