def solution(genres, plays): from collections import defaultdict songs = [] cnt = 0 answer = [] / # songs[]에 genres,plays,고유번호를 넣는다. for x, y in zip(genres, plays): songs.append([x, y, cnt]) cnt += 1 / # genres를 기준으로 정렬하되 plays를 순서대로 내림차순 정렬한다. songs.sort(key=lambda x: (x[0], x[1]), reverse=True) # default dic을 이용해 각 장르마다 plays의 합을 구한다. songs_dict = defaultdict(int) for k in songs: songs_dict[k[0]] += k[1] # plays를 기준으로 내림차순으로 장르를 구한다. dict_sort = sorted(songs_dict.items(), key=lambda x: x[1], reverse=True) / # genres에서 만든 요소들을 temp에 넣은 후 2개의 number만을 answer에 입력시킨다. for z in dict_sort: temp = [] temp = [x for x in songs if x[0] == z[0]] if len(temp) >= 2: answer.extend([temp[0][2], temp[1][2]]) else: answer.append(temp[0][2]) return answer
너무 코드가 긴것같다...
특히 temp에서 answer에 number를 효과적으로 넣는 방법을 알아보아야 겠다.