计算列表中的出现次数

时间:2015-04-11 22:58:06

标签: python python-2.7

我有两个这样的列表:

prefix = ['b', 'bo', 'br'] 
word = ['bring', 'boring', 'bold', 'bells']

如何计算列表字中每个前缀的次数?

它应该返回

[4, 2, 1]

1 个答案:

答案 0 :(得分:3)

使用列表理解,str.startswithsum

[sum(w.startswith(p) for w in word) for p in prefix] # [4, 2, 1]