티스토리 뷰

python

itertools / collections module

jeongyeji 2021. 3. 8. 00:10

📌 곱집합(Cartesian product) 구하기 - product

for문을 사용하여 구하는 방법

iterable1 = 'ABCD'
iterable2 = 'xy'
iterable3 = '1234'

for value1 in iterable1:
    for value2 in iterable2:
        for value3 in iterable3:
            print(value1, value2, value3)

itertools.product를 사용하여 구하는 방법

import itertools

iterable1 = 'ABCD'
iterable2 = 'xy'
iterable3 = '1234'
print(list(itertools.product(iterable1, iterable2, iterable3)))

📌 2차원 리스트를 1차원 리스트로 만들기 - from_iterable

문자열을 담은 2차원 리스트를 1차원 리스트로 반환

내가 쓴 코드

def solution(mylist):
    answer = []
    for i in mylist:
    	# 방법 1
    	answer += element
        # 방법 2
        for j in i:
            answer.append(j)
    return answer

for문을 사용하지 않는 방법

my_list = [[1, 2], [3, 4], [5, 6]]

# 방법 1 - sum 함수
answer = sum(my_list, [])

# 방법 2 - itertools.chain
import itertools
list(itertools.chain.from_iterable(my_list))

# 방법 3 - itertools와 unpacking
import itertools
list(itertools.chain(*my_list))

# 방법 4 - list comprehension 이용
[element for array in my_list for element in array]

# 방법 5 - reduce 함수 이용 1
from functools import reduce
list(reduce(lambda x, y: x+y, my_list))

# 방법 6 - reduce 함수 이용 2
from functools import reduce
import operator
list(reduce(operator.add, my_list))

# 방법 7 - numpy 라이브러리의 flatten 이용
# 리스트 내 각 원소의 길이가 동일한 경우에만 사용 가능
import numpy as np
np.array(my_list).flatten().tolist()

📌 순열과 조합 - combinations, permutations

 

순열은 itertools.permutation를 통해서, 조합은 itertools.combinations를 통해서 구할 수 있다.
itertools.permutation(iterable, r) : if r is not specified or is None, r defaults to the length of the iterable

import itertools

pool = ['A', 'B', 'C']
print(list(map(''.join, itertools.permutations(pool)))) # 3개의 원소로 수열 만들기
print(list(map(''.join, itertools.permutations(pool, 2)))) # 2개의 원소로 수열 만들기

📌 가장 많이 등장하는 알파벳 찾기 - counter

내가 쓴 코드

my_str = input().strip()
count = {}
max = 0
for i in my_str:
    if i in count:
        count[i] += 1
    else:
        count[i] = 1
    if count[i] > max:
        max = count[i]

mylist = []
for key in count:
    if max == count[key]:
        mylist.append(key)
mylist.sort()
str = ''

for i in mylist:
  str += i
print(str)

수정한 코드

import collections
my_str = input().strip()
c = dict(collections.Counter(my_str))
max = 0
str = ''
for i in c:
  if c[i] > max:
    c[i] = max

for i in c:
  if c[i] == max:
    str += i

print(''.join(sorted(str)))

most_common을 이용한 코드

c = collections.Counter(my_str)
str = ''
max = c.most_common(1)[0][1]
for i in c.most_common():
  if i[1] == max:
    str += i[0]
print(''.join(sorted(str)))

for문을 이용하는 경우 코드가 복잡해진다.

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 7, 9, 1, 2, 3, 3, 5, 2, 6, 8, 9, 0, 1, 1, 4, 7, 0]
answer = {}
for number in my_list:
    try:
        answer[number] += 1
    except KeyError:
        answer[number] = 1

print(answer[1]) # = 4
print(answer[3])  # = 3
print(answer[100])  # =  raise KeyError

python의 collections.Counter를 이용하면 간단한 코드를 만들 수 있다.

import collections
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 7, 9, 1, 2, 3, 3, 5, 2, 6, 8, 9, 0, 1, 1, 4, 7, 0]
answer = collections.Counter(my_list)

print(answer[1]) # = 4
print(answer[3])  # = 3
print(answer[100]) # = 0

프로그래머스 - 파이썬을 파이썬답게 강의를 듣고 정리한 내용
programmers.co.kr/learn/courses/4008

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/04   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
글 보관함