**方法一:使用函数counter,快速获取list中每个元素出现的次数**
from collections import Counter
list = [1,2,3,4,5,4,3,7,2,8,1]
num_Count=counter(list)
print(num_count)
def count(list):
return count(list)
print(count(list))
以上两种都可以
结果 {1: 2, 2: 2, 3: 2, 4: 2, 5: 1, 7: 1, 8: 1}
**方法二:使用for循环**
list = [1,2,3,4,5,4,3,7,2,8,1]
num_count={}
for i in list:
if i not in num_count:
num_count[i]=1
else:
num_count[i]+=1
print(num_count)
结果:{1: 2, 2: 2, 3: 2, 4: 2, 5: 1, 7: 1, 8: 1}
Python统计一个列表中每个元素出现的次数
最新推荐文章于 2024-05-04 03:23:49 发布