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}

你可能感兴趣的:(python)