4 回答

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

TA贡献1765条经验 获得超5个赞
您正在迭代字符串并检查字符串本身中的字母,所以if condition is always True在这种情况下是您的。
您需要的是在迭代字符串时维护一个单独的列表,其中包含您已经看到的所有字母。像这样,
uniq_list = []
a = 'abhishek'
count = 0
for 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)

TA贡献1780条经验 获得超1个赞
a = 'abhishek'
count = 0
uls = set()
nls = set()
for x in a:
if x not in uls:
uls.add(x)
else:
nls.add(x)
print(len(uls - nls))
它会打印字符,它只出现一次。
输出:6

TA贡献1963条经验 获得超6个赞
为什么不只是:
a = 'abhishek'
a.count('a') # or any other letter you want to count.
1
这是你想要的吗?
添加回答
举报