Sort Counter by frequency, then alphabetically in Python

后端 未结 4 2017
日久生厌
日久生厌 2020-12-17 02:25

I am trying to use counter to sort letters by occurrence, and put any that have the same frequency into alphabetical order, but I can\'t get access to the Value of the dicti

4条回答
  •  臣服心动
    2020-12-17 03:25

    You can try this:

    letter_count = collections.Counter("alphabet")
    
    the_letters = [a for a, b in letter_count.items() if b == 1]
    letters.sort()
    print("letters that occur only once:")
    
    for i in the_letters:
         print(i)
    

    This code creates a list of all letters that occur only once by using list comprehension, and then prints them all. items() returns a key-value pair, which can be used to determine if the value of a key is equal to one.

提交回复
热议问题