我有一个充满数字的巨大列表,我想根据它们的出现情况对它们进行排序。
我在 google 和 Chatgpt 上花了很长时间,找到了这个计数函数,但在所有示例中,该函数仅返回出现的数字之一。
sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
print(sample_list.count("a"))
print(sample_list.count("ab"))
这只会给我 A 和 Ab 的出现
如何打印所有数字以及出现的情况?
因此,如果我有这些数字(1, 1, 1, 2, 2, 3,),我希望它们像这样展示
1:3x
2:2x
3:1x
也是这样从多到少。
Counter
:
>>> from collections import Counter
>>> sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
>>> Counter(sample_list)
Counter({'ab': 3, 'a': 2, 'abc': 1})