简体   繁体   English

计算字母表的每次出现并将其存储在 Python 3 中的列表中

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

Suppose I have a string s假设我有一个字符串 s

s = "ebber"   

I want a list x, where x = [1,1,2,2,1]我想要一个列表 x,其中 x = [1,1,2,2,1]
We see the first occurrence of e so our first element in list x is 1, then we see the first occurrence of b so our next element in our list is 1, then we see our second occurrence of b so our next element in the list is 2, and so on.....我们看到 e 的第一次出现所以我们在列表 x 中的第一个元素是 1,然后我们看到 b 的第一次出现所以我们列表中的下一个元素是 1,然后我们看到我们第二次出现 b 所以我们在列表中的下一个元素是2,依此类推.....

How do I implement code to get this result in python?我如何实现代码以在 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