Skip to content

Instantly share code, notes, and snippets.

@jc3wrld999
Last active March 30, 2023 09:05
Show Gist options
  • Save jc3wrld999/d1a3dcb57b8f99679432413c18ca1d8a to your computer and use it in GitHub Desktop.
Save jc3wrld999/d1a3dcb57b8f99679432413c18ca1d8a to your computer and use it in GitHub Desktop.
animals = ['dog', 'cat', 'rabbit', 'tiger']
dic = {}
for animal in animals:
if animal in dic.keys():
dic[animal] += 1
else:
dic[animal] = 1
print(dic)
'''
기본적인 딕셔너리 사용법
위처럼 해당 key값이 존재하는지 조건문을 통해 파악하고 만약 딕셔너리 내부에 key값이 없다면 1초 초기화하는 과정을 거쳐야한다.
collections의 defaultdict로 초기화하면 이 작업을 생략할 수 있다.
'''
from collections import defaultdict
dic2 = defaultdict(int)
for animal in animals:
dic2[animal] += 1
print(dic2)
'''
defalutdict(list)
'''
animals = [('dog', 'Ricky'), ('cat', 'Momo'), ('rabbit', 'Jimmy'), ('cat', 'Chars'), ('cat', 'Pipy')]
dic3 = defaultdict(list)
for animal, name in animals:
dic3[animal].append(name)
print(dic3)
'''
output
{'dog': 1, 'cat': 1, 'rabbit': 1, 'tiger': 1}
defaultdict(<class 'int'>, {'dog': 1, 'cat': 1, 'rabbit': 1, 'tiger': 1})
defaultdict(<class 'list'>, {'dog': ['Ricky'], 'cat': ['Momo', 'Chars', 'Pipy'], 'rabbit': ['Jimmy']})
'''
####################### 순열, 조합 #############################
import itertools
'''
순열
itertools.permutations(['A', 'B', 'C'], 2)
>> A, B, C를 2개씩 순서를 고려한 경우의 수
>> [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
'''
arr = ['A', 'B', 'C']
nPr = itertools.permutations(arr, 2)
print(list(nPr))
'''
조합
itertools.combinations(['A', 'B', 'C'], 2)
[('A', 'B'), ('A', 'C'), ('B', 'C')]
'''
nCr = itertools.combinations(arr, 2)
print(list(nCr))
nPr = itertools.permutations([1, 1, 2], 3)
print(list(set(nPr)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment