Sort descending to the second numeric value of the tuple in the list

Asked 1 years ago, Updated 1 years ago, 80 views

word_list = [('this', 4), ('they', 3), ('that', 13), ('shall', 3), ('people', 3), ('nation', 5), ('here', 8), ('have', 5), ('great', 3), ('dedicated', 4), ('dead', 3)]

How do I arrange these lists in order of large numbers? (Crying)

python list tuple sorting

2022-09-22 19:54

2 Answers

Deeply...

The sorting algorithm (selective sorting) can be implemented, but the efficiency is slow to O(n2). It is usually very efficient to use functions that are already optimized for the primary module.

2)

The sorted function uses the timsort algorithm.

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)]


2022-09-22 19:54

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)

Compare the integers in the tuple value one by one.


2022-09-22 19:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.