Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reverse alphabetical order

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

like image 576
Henry McIntosh Avatar asked Apr 09 '15 04:04

Henry McIntosh


1 Answers

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')]
like image 93
Reut Sharabani Avatar answered Oct 01 '22 18:10

Reut Sharabani