def solution(clothes):
clothes_dict = {}
answer = 1
for clothe in clothes:
cloth_type = clothe[1]
if cloth_type not in clothes_dict:
clothes_dict[cloth_type] = 1
else:
clothes_dict[cloth_type] += 1
for value in clothes_dict.values():
answer *= (value + 1)
return answer - 1
clothes = [["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]]
>> 6
빈 딕셔너리 'clothes_dict'을 초기화한다.
'clothe' 리스트의 두 번째 요소인 의상의 종류 'cloth_type'을확인한다.
만약 'cloth_type'이 'clothes_dict' 딕셔너리에 존재하지 않는다면, 새로운 키로 현재 의상의 종류를 추가하고 값을 1로 설정한다.
만약 'cloth_type'이 'clothes_dict' 딕셔너리에 이미 존재한다면, 해당 종류의 의상이 이미 추가된 것이므로 값을 1 증가시킨다.
즉 'clothes_dict' 딕셔너리에는 각 의상의 종류별로 개수가 저장된다.
'clothes_dict' 딕셔너리의 값들을 확인하면서, 각 의상의 종류별로 선택 가능한 경우의 수를 계산한다.
'value'변수에 1을 더해서, 각 의상의 종류별로 선택하지 않은 경우를 포함시키고, 해당 값에 'answer' 변수에 누적곱으로 계산한다.
딕셔너리(Dictionary)
딕셔너리(Dictionary)는 키(key)와 값(value)의 쌍으로 이루어진 데이터를 저장하는 자료형이다. 딕셔너리는 중괄호 {}로 감싸고, 키와 값은 콜론 :으로 구분하여 표현한다.
clothes_dict = {}
for cloth in clothes:
cloth_type = cloth[1]
cloth_item = cloth[0]
if cloth_type not in clothes_dict:
clothes_dict[cloth_type] = [cloth_item]
else:
clothes_dict[cloth_type].append(cloth_item)
{
"headgear": ["yellow_hat", "green_turban"],
"eyewear": ["blue_sunglasses"]
}
for cloth in clothes:
cloth_type = cloth[1]
if cloth_type not in clothes_dict:
clothes_dict[cloth_type] = 1
else:
clothes_dict[cloth_type] += 1
{
"headgear": 2,
"eyewear": 1
}
# items(): (키, 값) 쌍을 나타내는 튜플로 구성된 객체를 반환
items = clothes_dict.items()
print(items)
# 출력: dict_items[('headgear', 2), ('eyewear', 1)])
# keys(): 키들로 구성된 객체를 반환
keys = clothes_dict.keys()
print(keys)
# 출력: dict_keys(['headgear', 'eyewear'])
# values(): 값들로 구성된 객체를 반환
values = clothes_dict.values()
print(values)
# 출력: dict_values([2, 1])
딕셔너리 뷰(View) 객체는 리스트 형태로 직접 반환되지는 않는다. 이 객체를 리스트로 변환하기 위해서는 반복(iteration)을 수행하거나list()함수를 사용하여 리스트로 변환해야 한다.