根据值对python进行排序

时间:2014-10-12 15:00:09

标签: python list sorting python-3.x

我为了它的乐趣而编写了一些代码

symbols = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "o", "p", "q",          "r", "s", "t", "u", "v", "w", "x", "y", "z"]
numbers = []
counter = 0

print("Enter Name")
name = input(">")
if name:
    new_name = list(name)

    for x in range(0, len(symbols)):
        count_name = new_name.count(symbols[x])
        numbers.append(count_name)
        if count_name:
            counter += 1
    print("Character amount =", counter)

    for x in range(0, len(numbers)):
        if numbers[x]:
            print(symbols[x], "=", numbers[x])
else:
    print("Input = NULL")

例如,输入您的姓名时 Roemer的

打印出类似这样的内容:

Character amount = 4    
e = 2    
m = 1    
o = 1    
r = 2    

但我想根据最常出现的角色进行排序

2 个答案:

答案 0 :(得分:1)

for number, symbol in sorted(zip(numbers, symbols), reverse=True):
    if number:
        print(symbol, number)

答案 1 :(得分:0)

如果不是家庭作业使用标准库计数器中的计数器提供所需的功能

from collections import Counter
x =Counter("roemer")
x.most_common()

>>> [('r', 2), ('e', 2), ('m', 1), ('o', 1)]

最常见的输出已经排序。可以使用Counter类使用列表理解的其他方法来获得所需格式的输出。