【问题标题】:Count number's digits following by line按行计算数字的位数
【发布时间】:2020-02-21 13:34:35
【问题描述】:

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

4 是 3 倍

3 是 3 次

1 是 2 倍

3 是 4 倍

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

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

【问题讨论】:

  • 为什么不能呢?是什么阻止了你?
  • 如果你使用脚本,那么你是如何找到这个词的(ab - 222)的,你将输入数字 2 三次

标签: python count numbers digits keypad


【解决方案1】:

使用正则表达式

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

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

【讨论】:

    【解决方案2】:

    您可以使用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
    

    【讨论】:

      【解决方案3】:

      这能解决问题吗? 该函数返回一个二维列表,其中包含每个数字及其找到的数量。然后你可以循环遍历列表并获取每个值

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-17
        • 1970-01-01
        • 2012-08-09
        相关资源
        最近更新 更多