我需要从单词列表中创建一个字母出现列表。
我的单词列表是[' song',' boom',' pow']
我想计算每个单词中的字母出现次数,然后按字母顺序将它们放入列表中。如果我的单词列表中没有与字母表中的每个字母匹配的字母,我仍然希望它在列表中打印0。
我没有在字母表中输入26个字符的字符串,而是使用string.ascii_lowercase
我不确定如何去做这件事。
然后我需要找出每个单词中的字母出现以及字母显示在哪个单词中。
然后输出应该如下:
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 4, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
'o' in 'song', 'boom', 'pow'
etc.
答案 0 :(得分:4)
第一部分可以像这样完成:
In [12]: seq = ['song', 'boom', 'pow']
In [13]: c = collections.Counter(''.join(seq))
In [14]: [c.get(l, 0) for l in string.ascii_lowercase]
Out[14]: [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 4, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]
关于第二部分,这里有一个提示:
In [23]: [w for w in seq if 'o' in w]
Out[23]: ['song', 'boom', 'pow']
答案 1 :(得分:1)
from collections import OrderedDict
from string import ascii_lowercase
l = ['song', 'boom', 'pow']
od = OrderedDict(((k,0) for k in ascii_lowercase)) # create dict from alph with initial val of 0
for word in l:
for let in word:
o[let] += 1 # increase value by 1 for each letter in the words
print(od.values()) # ordereddict keeps order so just print values
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 4, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]
for k in od:
for word in l:
if k in word:
print(k,word)
('b', 'boom')
('g', 'song')
('m', 'boom')
('n', 'song')
('o', 'song')
('o', 'boom')
('o', 'pow')
('p', 'pow')
('s', 'song')
('w', 'pow')
处理完成,退出代码为0
答案 2 :(得分:0)
另一种对我来说很自然的方式:
>>> from string import ascii_lowercase
>>> words= ['song', 'boom', 'pow']
>>> s=''.join(words)
>>> [s.count(c) for c in ascii_lowercase]
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 4, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]
对于第二部分,只需使用嵌套循环:
for c in ascii_lowercase:
li=[]
for word in words:
if c in word:
li.append(word)
if li:
print '{} in {}'.format(c, ', '.join(li))
打印:
b in boom
g in song
m in boom
n in song
o in song, boom, pow
p in pow
s in song
w in pow