![](/img/trans.png)
[英]Python 3 add the total of numbers in a string which also contains letters
[英]count the total numbers of unique letters occurred once in a string in python?
a = 'abhishek'
count = 0
for x in a:
if x in a:
count += 1
print(count)
我試過這個,但它給了我字母的總數。 我只想要一個只出現一次的獨特后者。
len(set(a))
會給你唯一的字母數
編輯:添加說明
set(a)
返回字符串a
中所有唯一字符的容器(Python 稱之為set
)。 然后len()
獲取該集合的計數,該計數對應於字符串a
中唯一字符的計數。
您正在迭代字符串並檢查字符串本身中的字母,因此在這種情況下您的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)
為什么不只是:
a = 'abhishek' a.count('a') # or any other letter you want to count.
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))
它會打印字符,它只出現一次。
Output:6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.