Python reverse alphabetical order

后端 未结 3 720
庸人自扰
庸人自扰 2021-01-13 08:10

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 tupl

相关标签:
3条回答
  • 2021-01-13 08:43

    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')]
    
    0 讨论(0)
  • 2021-01-13 08:43

    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)]
    
    0 讨论(0)
  • 2021-01-13 09:08

    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')]
    
    0 讨论(0)
提交回复
热议问题