python 列表中相同元素个数统计方法

nums = ['224', '226', '219', '222', '226', '219', '222', '226', '219', '222', '226', '219',
 '226', '222' ,'219', '226', '222', '219', '226', '222', '219', '222', '226', '219',
 '226' ,'222', '219', '222', '226', '226', '219', '222', '226', '219', '222', '226',
 '219' ,'226', '222', '219', '222', '226', '219', '222', '226', '219', '226', '222',
 '219' ,'226', '222', '219', '226', '222', '219', '226', '222', '219', '222', '226',
 '219' ,'222', '226', '219', '222', '226', '226', '219', '222', '226', '226', '219',
 '222' ,'226', '219', '222', '226', '219', '222', '226', '226' ,'219', '222', '226',
 '226']
#方法一:
a={
    
    }
for i in nums:
    a[i] = nums.count(i)
print(a)  

输出结果:

{
    
    '219': 26, '222': 26, '224': 1, '226': 32}
#方法二:
my_dict = {
    
    }
for i in nums:
    if i in my_dict:
        my_dict[i] += 1
    else:
        my_dict[i] = 1
print(my_dict)

输出结果:

{
    
    '219': 26, '222': 26, '224': 1, '226': 32}
#方法三:
from collections import Counter
a = Counter(nums)
print(dict(a))

输出结果:

{
    
    '219': 26, '222': 26, '224': 1, '226': 32}

猜你喜欢

转载自blog.csdn.net/WANGYONGZIXUE/article/details/111576380
今日推荐