计数的字母总数字符串

问题描述:

一个=“人人生而宪法的权力下平等,托马斯·杰斐逊”计数的字母总数字符串

我知道a.count(“A”)将返回多少“A”有。但我想要统计有多少A,E,C和T,并将它们加在一起。非常感谢。

进出口使用Python3

+0

你需要分别计算每个字母还是只计算总数? – digitaLink

查找到collections.Counter

>>> from collections import Counter 
>>> import string 
>>> c = Counter(l for l in a if l in string.ascii_letters) 
>>> c 
Counter({'e': 11, 't': 6, 'o': 6, 'r': 5, 'n': 5, 'a': 4, 'l': 3, 'f': 3, 
     's': 3, 'u': 3, 'h': 3, 'i': 2, 'd': 2, 'c': 2, 'm': 2, 'A': 1, 
     'p': 1, 'w': 1, 'T': 1, 'J': 1, 'q': 1}) 
>>> sum(c.values()) 
66 
>>> c = Counter(l for l in a if l in 'AecT') 
>>> c 
Counter({'e': 11, 'c': 2, 'A': 1, 'T': 1}) 
>>> sum(c.values()) 
15 
+0

你可以通过将'string.ascii_letters'存储在一个集合 –

+0

'sum(c [x] for x in('A','e','c','T'))''中得到一些改进,因为OP想要“来统计有多少A,E,C和T,并将它们加在一起” –

+0

@JohnLaRooy确实,但样本量太小 - 对于设置的裸露150μs,20μs太小。 – AChampion

Python有一个很好的模块。使用计数器

from collections import Counter 
a = "All men are created equal under the power of the constitution, Thomas Jefferson" 
counter = Counter(a) 

print(counter) 

它会输出一个所有字母的字典作为关键字,值将是出现次数。

你可以使用正则表达式表达式来查找字母总数轻松

import re 
p = re.compile("\w") 
a = "All men are created equal under the power of the constitution, Thomas Jefferson" 
numberOfLetters = len(p.findall(a)) 

将返回66

如果你只是想A,E,C和T,你应该使用这个表达式代替:

p = re.compile("[A|e|c|T]") 

将返回15

只是用另一种方法尝试

map(lambda x: [x, a.count(x)], 'AecT') 

'a'是输入字符串。 'AecT'可以根据需要用所需的字母替换。

+1

重复''a''有点令人困惑,并且计数'a'会包括标点符号,所以改为OP的请求(或者可以使用'string.ascii_letters'作为字母) – AChampion