按行计算数字的数字

Count number's digits following by line

我有号码 444333113333,我想数一数这个号码中的每个不同数字。

4 是 3 倍

3是3倍

1是2倍

3是4倍

我想做的是制作一个脚本,将 phone 键盘点击转换为字母 就像这张照片 https://www.dcode.fr/tools/phone-keypad/images/keypad.png 如果我按 3 次数字 2,则字母为 'C'

我想在 python 中用它制作一个脚本,但我不能...

您可以使用itertools.groupby

num = 444333113333
numstr = str(num)

import itertools


for c, cgroup in itertools.groupby(numstr):
    print(f"{c} count = {len(list(cgroup))}")

输出:

4 count = 3
3 count = 3
1 count = 2
3 count = 4

使用正则表达式

import re
pattern = r"(\d)*"

text = '444333113333'

matcher = re.compile(pattern)
tokens = [match.group() for match in matcher.finditer(text)] #['444', '333', '11', '3333']

for token in tokens:
    print(token[0]+' is '+str(len(token))+' times')

输出

4 is 3 times
3 is 3 times
1 is 2 times
3 is 4 times

这样做有用吗? 函数 returns 一个二维列表,其中包含每个数字及其找到的数量。然后您可以循环浏览列表并获取所有值

def count_digits(num):
    #making sure num is a string
    #adding an extra space so that the code below doesn't skip the last digit
    #there is a better way of doing it but I can't seem to figure out it on spot
    #essemtially it ignores the last set of char so I am just adding a space
    #which will be ignored
    num = str(num) + " "

    quantity = []

    prev_char = num[0]
    count = 0

    for i in num:

        if i != prev_char:

            quantity.append([prev_char,count])
            count = 1
            prev_char = i

        elif i.rfind(i) == ([len(num)-1]):
            quantity.append([prev_char,count])
            count = 1
            prev_char = i

        else:
            count = count + 1






    return quantity

num = 444333113333
quantity = count_digits(num)

for i in quantity:
    print(str(i[0]) + " is " + str(i[1]) + " times" )

输出:

4 is 3 times
3 is 3 times
1 is 2 times
3 is 4 times