4 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
len(set(a))
會(huì)給你唯一的字母數(shù)
編輯:添加說(shuō)明
set(a)
返回字符串中所有唯一字符的容器(Python 稱之為set
)a
。然后len()
獲取該集合的計(jì)數(shù),該計(jì)數(shù)對(duì)應(yīng)于 string 中唯一字符的計(jì)數(shù)a
。

TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
您正在迭代字符串并檢查字符串本身中的字母,所以if condition is always True在這種情況下是您的。
您需要的是在迭代字符串時(shí)維護(hù)一個(gè)單獨(dú)的列表,其中包含您已經(jīng)看到的所有字母。像這樣,
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貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
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))
它會(huì)打印字符,它只出現(xiàn)一次。
輸出:6

TA貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個(gè)贊
為什么不只是:
a = 'abhishek'
a.count('a') # or any other letter you want to count.
1
這是你想要的嗎?
添加回答
舉報(bào)