样本输出

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)

10-08 17:18