重复字符计数器

时间:2019-04-04 03:46:12

标签: python-3.6

美好的一天:

想问一个关于我在Python 3.6上的代码的简单问题

我想计算所有重复的字符

这是我处理过的代码的示例:


name01 = input("1st Name: ")

ch_name01 = []
bl_char = False
i = 0
for ch in name01:

    i = 0

    for ich in ch_name01:

        bl_char = False

        if ich[i][0] == ch:
            bl_char = True
            #ch_name01[i][1] = ch_name01[i][1] + 1
            #print(str(ch_name01[i][0]) + " - " + str(ch_name01[i][1]))

        if not bl_char:
            i = i + 1


    if bl_char == False:
        ch_name01.append([ch, 1])

print(ch_name01)

#print(ch_name01)

例如输入"aabbccddef" 想要返回a = 2, b = 2, c = 2, d = 2

但是它将返回错误消息

"TypeError: 'int' object is not subscriptable"

if ich[i][0] == ch:

1 个答案:

答案 0 :(得分:0)

在这里使用字典会使您的生活变得更加轻松。

name01 = input("1st Name: ")

ch_name01 = {}             # New dictionary 
for ch in name01:          # For every char in the input string
    if ch in ch_name01:    # If that char already has an entry in the dictionary
        ch_name01[ch] += 1 # increment that char's entry's integer value
    else:                  # the char hasn't been added to the dictionary yet
        ch_name01[ch] = 1  # add a new dictionary entry with an integer value of 1
print(ch_name01)

提供aabbccddef的输入会产生:

{'a': 2, 'b': 2, 'c': 2, 'd': 2, 'e': 1, 'f': 1}

编辑: 我添加了代码注释来解释每一行的作用