python计算书页码的统计数字问题实例

yipeiwu_com5年前Python基础

本文实例讲述了python计算书页码的统计数字问题,是Python程序设计中一个比较典型的应用实例。分享给大家供大家参考。具体如下:

问题描述:对给定页码n,计算出全部页码中分别用到多少次数字0,1,2,3,4...,9

实例代码如下:

def count_num1(page_num): 
  num_zero = 0 
  num_one = 0 
  num_two = 0 
  num_three = 0 
  num_four = 0 
  num_five = 0 
  num_six = 0 
  num_seven = 0 
  num_eight = 0 
  num_nine = 0 
  page_list = range(1,page_num + 1) 
  for page in page_list: 
    page = str(page) 
    num_zero += page.count('0') 
    num_one += page.count('1') 
    num_two += page.count('2') 
    num_three += page.count('3') 
    num_four += page.count('4') 
    num_five += page.count('5') 
    num_six += page.count('6') 
    num_seven += page.count('7') 
    num_eight += page.count('8') 
    num_nine += page.count('9') 
  result = [num_zero,num_one,num_two,num_three,num_four,num_five,num_six,num_seven,num_eight,num_nine] 
  return result 
 
print count_num1(13) 

上面这段代码略显臃肿,所以改了下代码。

改后的代码如下:

def count_num2(page_num): 
  page_list = range(1,page_num + 1) 
  result = [0 for i in range(10)] 
  for page in page_list: 
    page = str(page) 
    for i in range(10): 
      temp = page.count(str(i)) 
      result[i] += temp 
  return result
print count_num2(13)

本文实例测试运行环境为Python2.7.6

程序输出结果为:

[1, 6, 2, 2, 1, 1, 1, 1, 1, 1]

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python之list对应元素求和的方法

本次分享将讲述如何在Python中对多个list的对应元素求和,前提是每个list的长度一样。比如:a=[1,2,3], b=[2,3,4], c=[3,4,5], 对a,b,c的对应元...

在python中使用with打开多个文件的方法

虽然初恋是java, 可是最近是越来越喜欢python, 所以决定追根溯源好好了解下python的原理,架构等等.小脑袋瓜不太好使,只能记录下慢慢进步吧 使用with打开文件的好处不多说...

python随机生成指定长度密码的方法

本文实例讲述了python随机生成指定长度密码的方法。分享给大家供大家参考。具体如下: 下面的python代码通过对各种字符进行随机组合生成一个指定长度的随机密码 python中的str...

使用IronPython把Python脚本集成到.NET程序中的教程

从两个优秀的世界各取所需,更高效的复用代码。想想就醉了,.NET和python融合了。“懒惰”的程序员们,还等什么? Jesse Smith为您展示如何两个语言来服务同一个.NET程序。...

全面了解Python的getattr(),setattr(),delattr(),hasattr()

1. getattr()函数是Python自省的核心函数,具体使用大体如下: class A: def __init__(self): self.name = 'zhangji...