Python 给定一个列表,打印列表中每个整数出现的次数

Python 给定一个列表,打印列表中每个整数出现的次数,python,Python,例如,L=[1,2,2,3,4,9] 预期产出: 1例发生1次 2例发生2次 3例发生1次 4例发生1次 9发生1次请尝试以下操作: import collections for k, freq in collections.Counter(L).items(): print(f"{k} occurred {freq} times") 如果要将其打印为字符串: for i in set(L): print(f"{i} occurred {L.co

例如,L=[1,2,2,3,4,9] 预期产出: 1例发生1次 2例发生2次 3例发生1次 4例发生1次 9发生1次

请尝试以下操作:

import collections

for k, freq in collections.Counter(L).items():
    print(f"{k} occurred {freq} times")

如果要将其打印为字符串:

for i in set(L):
    print(f"{i} occurred {L.count(i)} times"
如果要存储这些计数以便稍后在代码中使用,请使用字典:
d={i:L.count(i)for i in set(L)

collections.Counter(L)这是否回答了您的问题?欢迎使用stackoverflow,我们希望您在发布问题之前进行研究。搜索将得到您需要的。这两种实现都是不必要的低效实现