【问题标题】:Display each element of the dictionary on a new line working with Counter在使用 Counter 的新行上显示字典的每个元素
【发布时间】:2021-12-17 19:00:09
【问题描述】:

我有一个随机颜色的数组。有重复的元素。例如:

mass = ['white','black','white'...]

我需要计算它们,所以我决定使用计数器:

mass_count = Counter(mass)
print (mass_count)

What I've got

我想在新行上显示字典的每个元素。我已经使用了该代码:

keys = [k for k in mass_count]
for i, key in enumerate(keys):      
    print("\n" + str(list(mass_count.keys())[i]) + ": " + str(mass_count[keys[i]]))

What I've got #2

我想要的一切,除了一件事:在我的第一个结果中,所有元素都从最大值显示到最小值,但在第二个结果中违反了这个顺序。所以我想要:

白色:22

黑色:14

天蓝色:6

...

我怎样才能实现它?谢谢。

【问题讨论】:

    标签: python dictionary counter


    【解决方案1】:

    你可以使用Counter.most_common()method

    for color, value in mass_count.most_common():
        print(f"{color}: {value}")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-02
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 2022-10-24
      • 2019-01-10
      相关资源
      最近更新 更多