小九九 发表于 2023-8-14 11:04:32

编写一个程序,计算一个字符串中各个字符出现的次数。

下面是计算一个字符串中各个字符出现次数的程序示例:

def count_characters(string):
    # 初始化计数字典
    count_dict = {}

    # 遍历字符串
    for char in string:
      if char in count_dict:
            count_dict += 1
      else:
            count_dict = 1
   
    # 返回计数字典
    return count_dict

# 测试示例
input_string = "hello world"
result = count_characters(input_string)
print(result)
运行上述程序,将输出以下结果:
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
这个程序通过遍历字符串,并使用字典来记录每个字符出现的次数。对于每个字符,如果它已经在字典中,就将其对应的值加 1;否则,将其添加到字典中,并将其值初始化为 1。在上述示例中,输入字符串为 "hello world",字母 'h' 出现了 1 次,字母 'e' 出现了 1 次,字母 'l' 出现了 3 次,字母 'o' 出现了 2 次,空格字符 ' ' 出现了 1 次,字母 'w'、'r'、'd' 分别出现了 1 次。最后将计数字典返回。
页: [1]
查看完整版本: 编写一个程序,计算一个字符串中各个字符出现的次数。