[英]How do I count the character in a string
我想計算一個字符串中有多少個字符,但不計算出現次數。 例如:
test_list=("aabbccddee")
我希望結果為 5,因為有 5 個字符:
(a,b,c,d,e)
我嘗試使用 len 函數和計數,也
from collections import defaultdict
這能解決您的問題嗎?
from collections import Counter
given_string = "aabbccddee"
result = Counter(given_string)
print(len(result))
在 python 中使用set
。
len(set("aabbccddee"))
# returns 5
Python 中的set
不包含像數學中的集合那樣重復的成員(也不是有序的)。 定義set
的另一種語法就像沒有鍵的字典:
set_example = { 1, 2, 2, 3, 3, 3 }
# set_example is { 1, 2, 3 }
試試這個:
your_str = 'aabbccddee'
result = len(set(your_str))
print(result)
set()
的替代方法:
len(dict.fromkeys(test_list))
#5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.