簡體   English   中英

計算字母表的每次出現並將其存儲在 Python 3 中的列表中

[英]Count each occurrence of alphabet and store it in a list in Python 3

假設我有一個字符串 s

s = "ebber"   

我想要一個列表 x,其中 x = [1,1,2,2,1]
我們看到 e 的第一次出現所以我們在列表 x 中的第一個元素是 1,然后我們看到 b 的第一次出現所以我們列表中的下一個元素是 1,然后我們看到我們第二次出現 b 所以我們在列表中的下一個元素是2,依此類推.....

我如何實現代碼以在 python 中獲得這個結果?

from collections import defaultdict

def count(s):
    d, ls = defaultdict(int), []
    for e in s:
        d[e] += 1 # increment counter of char
        ls.append(d[e]) # add counter
    return ls

count("ebber") # [1, 1, 2, 2, 1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM