示例输出
Enter numbers separated by spaces :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
So I'm a total newbie at python but I was thinking of starting off like this :
d = {}
user = input("Enter numbers separated by spaces :")
data = user.split()
除了我尝试过的每个循环都一直说我不能将 str() 转换为 int(),如果有任何帮助,我将不胜感激,我已经盯着这个问题看了几个小时了..这是我尝试过的输入是字符串,试图为字典实现类似的东西
def countdigits (aString):
c = 10 * [0]
for e in aString:
c[int(e)] += 1
return c
def main ():
n = 0
for v in (countdigits(str(input('Enter a string: ')))):
if v == 1:
print(n, "occurs 1 time")
elif v!=0:
print(n, "occurs", v, "times")
n += 1
main()
对于给定的输出(但使用字典),我想要一个类似的解决方案
请您参考如下方法:
尝试
d = {i:data.count(i) for i in data}
for k,v in d:
print "{0} occurs {1} times\n".format(k,v)
或喜欢以下评论中的示例:
import collections
for a,b in collections.Counter(data).items():
print "{0} occurs {1} times\n".format(a,b)
