Python 颠倒字母顺序

Python reverse alphabetical order

我有这个输出: [(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')]

给你:

from collections import Counter
from operator import itemgetter

def top5_words(text):
  tally = Counter()
  for word in text.split():
      tally[word] += 1
  vals = tally.items()
  vals.sort(key=itemgetter(0))
  vals.sort(key=itemgetter(1), reverse=True)
  return vals

print top5_words("one one was a racehorse two two was one too")
# [('one', 3), ('two', 2), ('was', 2), ('a', 1), ('racehorse', 1), ('too', 1)]

定义列表:

>>> mylist = [(3, 'one'), (2, 'was'), (2, 'two'), (1, 'too'), (1, 'racehorse'), (1, 'a')]

对列表进行排序:

>>> sorted(mylist, key=lambda x: (-x[0], x[1]), reverse=True)
[(1, 'too'), (1, 'racehorse'), (1, 'a'), (2, 'was'), (2, 'two'), (3, 'one')]