리스트 내의 튜플의 두번째 숫자 값으로 내림 차순 정렬
조회수 2928회
word_list = [('this', 4), ('they', 3), ('that', 13), ('shall', 3), ('people', 3), ('nation', 5), ('here', 8), ('have', 5), ('great', 3), ('dedicated', 4), ('dead', 3)]
이러한 리스트가 있는데 숫자가 큰 순서대로 정렬하려면 어떻게 해야 하나요? ㅠㅠㅠㅠㅠ
-
(•́ ✖ •̀)
알 수 없는 사용자 - 〉
2 답변
-
심화적으로......
정렬 알고리듬(선택정렬)을 구현해도 되나 효율이 O(n2) 으로 느립니다. 이미 기본 모듈에 최적화된 펑션을 사용하는 것이 보통 좋은 효율을 냅니다.
sorted 펑션은 timsort 알고리듬을 사용합니다.
import operator word_list = [('this', 4), ('they', 3), ('that', 13), ('shall', 3), ('people', 3), ('nation', 5), ('here', 8), ('have', 5), ('great', 3), ('dedicated', 4), ('dead', 3)] sorted(word_list, key=operator.itemgetter(1), reverse=True) [('that', 13), ('here', 8), ('nation', 5), ('have', 5), ('this', 4), ('dedicated', 4), ('they', 3), ('shall', 3), ('people', 3), ('great', 3), ('dead', 3)]
-
word_list = [('this', 4), ('they', 3), ('that', 13), ('shall', 3), ('people', 3), ('nation', 5), ('here', 8), ('have', 5), ('great', 3), ('dedicated', 4), ('dead', 3)] a = len(word_list) for i in range(a - 1): for j in range(a - i - 1): if word_list[j][1] < word_list[j + 1][1]: temp = word_list[j] word_list[j] = word_list[j + 1] word_list[j + 1] = temp continue continue print(word_list)
튜플값 안에 있는 정수를 하나씩 서로 비교하면 됩니다.
-
(•́ ✖ •̀)
알 수 없는 사용자
-
댓글 입력