计算以字母Python开头的单词数

Jus*_*tin 0 python dictionary count

我正在尝试计算列表中以字母表中每个字母开头的单词数.我尝试过很多东西,似乎没什么用.最终结果应该是这样的:

list = ['the', 'big', 'bad', 'dog']
a: 0
b: 2
c: 0
d: 1
Run Code Online (Sandbox Code Playgroud)

我想我应该用字典做些什么,对吧?

daw*_*awg 6

from collections import Counter
print Counter(s[0] for s in  ['the', 'big', 'bad', 'dog'])
# Counter({'b': 2, 't': 1, 'd': 1})
Run Code Online (Sandbox Code Playgroud)

如果你想要零,你可以这样做:

import string

di={}.fromkeys(string.ascii_letters,0)
for word in ['the', 'big', 'bad', 'dog']:
    di[word[0]]+=1

print di    
Run Code Online (Sandbox Code Playgroud)

如果您只想'A'计算'a':

di={}.fromkeys(string.ascii_lowercase,0)
for word in ['the', 'big', 'bad', 'dog']:
    di[word[0].lower()]+=1
# {'a': 0, 'c': 0, 'b': 2, 'e': 0, 'd': 1, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0, 'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0, 't': 1, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}
Run Code Online (Sandbox Code Playgroud)

你可以将这两者结合起来:

c=Counter({}.fromkeys(string.ascii_lowercase,0))
c.update(s[0].lower() for s in  ['the', 'big', 'bad', 'dog'])
print c
# Counter({'b': 2, 'd': 1, 't': 1, 'a': 0, 'c': 0, 'e': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0, 'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0})
Run Code Online (Sandbox Code Playgroud)