Python reverse alphabetical order

左心房为你撑大大i 提交于 2019-12-04 01:30:35

问题


I have this output: [(3, 'one'), (2, 'was'), (2, 'two'), (1, 'too'), (1, 'racehorse'), (1, 'a')]

and i need to make it so that the tuples with the same number are placed in reverse alphabetical order inside the list. This is my code:

`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`

the text i put in was: one one was a racehorse two two was one too


回答1:


You can use list.sort with the reverse argument:

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



回答2:


Define the list:

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

Sort the list:

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



回答3:


Here you go:

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


来源:https://stackoverflow.com/questions/29529641/python-reverse-alphabetical-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!