Python反向字母顺序
问题内容:
我有这个输出: [(3, 'one'), (2, 'was'), (2, 'two'), (1, 'too'), (1, 'racehorse'), (1, 'a')]
我需要这样做,以便将具有相同编号的元组以相反的字母顺序放在列表内。这是我的代码:
`def top5_words(text):
split_text = text.split()
tally = {}
for word in split_text:
if word in tally:
tally[word] += 1
else:
tally[word] = 1
vals = []
for key, val in tally.items():
vals.append((val, key))
reverse_vals = sorted(vals, reverse = True)
return reverse_vals`
我输入的文字是:一匹是赛马,二匹也是一匹
问题答案:
您可以使用list.sort
反向参数:
>>> l = [(3, 'one'), (2, 'was'), (2, 'two'), (1, 'too'), (1, 'racehorse'), (1, 'a')]
>>> l.sort(key=lambda x: x[1], reverse=True)
>>> l.sort(key=lambda x: x[0])
>>> l
[(1, 'too'), (1, 'racehorse'), (1, 'a'), (2, 'was'), (2, 'two'), (3, 'one')]