正确输出用于计算字符串中每个数字出现次数的函数 [英] Correct output for function that counts occurrences of each digit in a string

查看:165
本文介绍了正确输出用于计算字符串中每个数字出现次数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户输入一串数字,例如让我说... 122033

I want the output of the code to be something like this if the user enters a string of numbers like let's say... 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]

This is the program that I have so far. At it's current state, if a user enters something like 122033 the output is: [1,1,2,2]

注意:我无法使用集合

推荐答案

没有 collections.Counter ,这是一个漂亮的地方简短高效的解决方案:

Without collections.Counter, here is a pretty short and efficient solution:

>>> 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循环行进行一些修改:

As Peter DeGlopper notes in the comment below, this solution will work for any character set, not just digits. If however you want it to only work with digits, all you need to do is make a slight modification to the for-loop line:

for a,b in sorted((c, inp.count(c)) for c in set(inp) if c.isdigit()):

在末尾加上如果c.isdigit()将使其仅捕获数字。

Adding if c.isdigit() to the end of that will make it only capture digits.

这篇关于正确输出用于计算字符串中每个数字出现次数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆