1. 程式人生 > >統計字串中的字元個數 python程式設計

統計字串中的字元個數 python程式設計

問題描述:

題目內容:

定義函式countchar()按字母表順序統計字串中所有出現的字母的個數(允許輸入大寫字元,並且計數時不區分大小寫)。形如:

  1. def countchar(string):
  2.       ... ...
  3.      return a list
  4. if __name__ == "__main__":
  5.      string = input()
  6.      ... ...
  7.      print(countchar(string))

輸入格式:

字串

輸出格式:

列表

輸入樣例:

Hello, World!

輸出樣例:

[0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 3, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0]

時間限制:2000ms記憶體限制:32000kb

python實現實現:

def countchar(string):
    for i in string.lower():
        if i in alphabetic_list:
            alphabet_no_list[alphabetic_list.index(i)] += 1
    return alphabet_no_list

if __name__ == "__main__":
    string = input()
    alphabetic_list =  'abcdefghijklmnopqrstuvwxyz'
    alphabet_no_list = [0]*26
    print(countchar(string))