我希望代码的输出是这样的,如果用户输入一串数字,就像让我们说... 122033
Enter string of numbers: 122033
0 occurs 1 time
1 occurs 1 time
2 occurs 2 times
3 occurs 2 times
def count_digits(s):
res = [0]*10
for x in s:
res[int(x)] += 1
while 0 in res:
res.remove(0)
return res
def main():
s=input("Enter string of numbers: ")
print(count_digits(s))
main()
这是我到目前为止的程序。在当前状态下,如果用户输入类似122033的内容,则输出为: [1,1,2,2]
注意:我不能使用集合。
答案 0 :(得分:2)
您非常接近工作解决方案,但删除所有0计数条目会更改列表的索引。您已经需要编写一些自定义的漂亮打印代码,所以只需保留0并跳过计数为0的元素。也许是这样的:
def count_digits(s):
res = [0]*10
for x in s:
res[int(x)] += 1
return res
def print_counts(counts):
for (index, count) in enumerate(counts):
if count == 1:
print("%d occurs %d time" % (index, count))
elif count > 1:
print("%d occurs %d times" % (index, count))
def main():
s=input("Enter string of numbers: ")
print_counts(count_digits(s))
答案 1 :(得分:2)
如果没有collections.Counter
,这是一个非常简短有效的解决方案:
>>> def count_digits(inp):
... for a,b in sorted((c, inp.count(c)) for c in set(inp)):
... print("{} occurs {} times".format(a, b))
...
>>> mystr = input("Enter string of numbers: ")
Enter string of numbers: 122033
>>> count_digits(mystr)
0 occurs 1 times
1 occurs 1 times
2 occurs 2 times
3 occurs 2 times
>>>
正如Peter DeGlopper在下面的评论中指出的那样,这个解决方案适用于任何字符集,而不仅仅是数字。但是,如果您希望它只能使用数字,那么您需要做的就是对for循环线稍作修改:
for a,b in sorted((c, inp.count(c)) for c in set(inp) if c.isdigit()):
将if c.isdigit()
添加到其末尾将使其仅捕获数字。
答案 2 :(得分:0)
不使用计数器的方法:
d = {}
for i in somestring:
if i not in d:
d[i] = 1
else:
d[i] += 1
for k,v in d.iteritems():
print('{0} occurs {1} times'.format(k,v))