本文執行個體講述了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 resultprint count_num2(13)
本文執行個體測試回合環境為Python2.7.6
程式輸出結果為:
[1, 6, 2, 2, 1, 1, 1, 1, 1, 1]
希望本文所述對大家的Python程式設計有所協助。