【发布时间】:2013-11-14 23:24:29
【问题描述】:
如果我有一个数字列表(例如:- 1 2 3 3 2 2 2 1 3 4 5 3 ),我如何使用 python 中的字典来计算列表中每个数字的出现次数?
所以输出是这样的:
输入以空格分隔的数字:1 2 3 3 2 2 2 1 3 4 5 3
{'1': 2, '3': 4, '2': 4, '5': 1, '4': 1}
1 occurs 2 times
3 occurs 4 times
2 occurs 4 times
5 occurs one time
4 occurs one time
如果一个数字只出现一次,输出应该是“一次”。
这是我目前所拥有的:
numbers=input("Enter numbers separated by spaces:-")
count={}
for number in numbers:
if number in count:
count[number] = count[number]+1
else:
count[number] = 1
print(number)
但我的输出最终是最后一个数字,我输入有人可以帮助我吗?
好的,这就是我现在拥有的:
numbers = input("Enter numbers separated by spaces:-") # i.e. '1 2 3 3 2 2 2 1 3 4 5 3'
my_list = list(map(int, numbers.strip().split(' ')))
count = {}
for x in set(my_list):
count[x] = my_list.count(x)
print(count)
for key, value in count.items():
if value == 1:
print('{} occurs one time'.format(key))
else:
print('{} occurs {} times'.format(key, value))
这就是我现在拥有的,看起来还不错,如果有任何改进的方法,请告诉我。非常感谢大家
【问题讨论】:
-
计数器未定义是我得到的
标签: python dictionary counter