В этом сценарии вы должны создать свою собственную функцию сортировки, которая возвращает кортеж (частота, длина, индекс). Однако, поскольку мы сортируем с использованием флага reverse = True
, нам нужен не исходный индекс, а длина разделенных слов за вычетом индекса, так как это собирает последний вес в сортировке.
from operator import itemgetter
first = itemgetter(0)
second = itemgetter(1)
words = s.split()
d = dict()
for word in words:
if word in d:
d[word] += 1
else:
d[word] = 1
def custom_sort(tup):
frequency = second(tup)
length = len(first(tup))
idx = len(words) - words.index(first(tup))
return (frequency, length, idx)
sorted(d.items(), key=custom_sort, reverse=True)
[('country', 2),
('India', 2),
('towards', 1),
('making', 1),
('better', 1),
('great', 1),
('will', 1),
('work', 1),
('and', 1),
('our', 1),
('the', 1),
('is', 1),
('a', 1),
('I', 1)]
list(map(first, sorted(d.items(), key=custom_sort, reverse=True)))
['country',
'India',
'towards',
'making',
'better',
'great',
'will',
'work',
'and',
'our',
'the',
'is',
'a',
'I']