我有一个工作代码,但是,我希望学习一个更Pythonic的版本,因为我觉得我的代码非常笨重。
这个想法是计算列表(“名称”)中出现的次数并对其后代进行排序。
aux_list = []
names = ["Jessica", "John", "Steve", "John", "John", "Steve"]
total = {}
for name in names:
if name is not aux_list:
aux_list.append(name)
count = names.count(name)
key = { name : count }
total.update(key)
# sort desc
sorted_total = sorted(total, key=total.get, reverse=True)
# Desired output: <NAME> <TOTAL> DESC ORDER
# John 3
# Steve 2
# Jessica 1
for r in sorted_total:
print(r, total[r])
Run Code Online (Sandbox Code Playgroud)
from collections import Counter
names = ["Jessica", "John", "Steve", "John", "John", "Steve"]
res = Counter(names).most_common()
print(res)
Run Code Online (Sandbox Code Playgroud)
输出
[('John', 3), ('Steve', 2), ('Jessica', 1)]
Run Code Online (Sandbox Code Playgroud)