计算python字符串中出现一次的唯一字母总数?

a = 'abhishek'

count = 0


for x in a:

    if x in a:

        count += 1 

print(count) 

我试过这个,但它给了我字母的总数。我只想要一个只出现一次的独特后者。


白衣非少年
浏览 141回答 4
4回答

倚天杖

len(set(a))会给你唯一的字母数编辑:添加说明set(a)返回字符串中所有唯一字符的容器(Python 称之为set)a。然后len()获取该集合的计数,该计数对应于 string 中唯一字符的计数a。

POPMUISE

您正在迭代字符串并检查字符串本身中的字母,所以if condition is always True在这种情况下是您的。您需要的是在迭代字符串时维护一个单独的列表,其中包含您已经看到的所有字母。像这样,uniq_list = []a = 'abhishek'count = 0for x in a:    if x not in uniq_list: # check if the letter is already seen.        count += 1 # increase the counter only when the letter is not seen.        uniq_list.append(x) # add the letter in the list to mark it as seen.print(count) 

慕神8447489

a = 'abhishek'count = 0uls = set()nls = set()for x in a:    if x not in uls:        uls.add(x)    else:        nls.add(x)print(len(uls - nls))它会打印字符,它只出现一次。输出:6

神不在的星期二

为什么不只是:a = 'abhishek' a.count('a') # or any other letter you want to count.1这是你想要的吗?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python