Python反向字母顺序

时间:2015-04-09 04:14:04

标签: python alphabetical-sort

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

我输入的文字是:一个是赛马,两个两个也是一个

3 个答案:

答案 0 :(得分:4)

您可以将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')]

答案 1 :(得分:4)

定义清单:

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

答案 2 :(得分:1)

你走了:

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