Python - 计算列表子串中字符串的出现次数

the*_*ler 4 python string substring list

我知道计算列表项的简单出现就像这样简单:

>>>[1, 2, 3, 4, 1, 4, 1].count(1)
3
Run Code Online (Sandbox Code Playgroud)

但我想知道怎么做是每次字符串出现在列表条目的子字符串中时计数.

例如,我想看看foo列表中出现了多少次data:

data = ["the foo is all fooed", "the bar is all barred", "foo is now a bar"]
Run Code Online (Sandbox Code Playgroud)

这样做:

d_count = data.count('foo')
print("d_count:", d_count)
Run Code Online (Sandbox Code Playgroud)

生产:

d_count: 0

我也尝试过:

d_count = data.count(any('foo' in s for s in data))
print("d_count:", d_count)
Run Code Online (Sandbox Code Playgroud)

但这也产生:

d_count: 0

我想知道如何计算列表中每次出现的子串外观,谢谢.

Chr*_*ean 13

您可以使用sum内置函数执行此操作.不需要使用list.count:

>>> data = ["the foo is all fooed", "the bar is all barred", "foo is now a bar"]
>>> sum('foo' in s for s in data)
2
>>>
Run Code Online (Sandbox Code Playgroud)

此代码有效,因为布尔值可以视为整数.每次'foo'出现在字符串元素中,True都会返回.整数值True1.所以就好像每次'foo'都在一个字符串中,我们返回1.因此,对1返回的总和将产生1元素中出现的次数.

编写上述代码可能更明确但更等效的方法是:

>>> sum(1 for s in data if 'foo' in s)
2
>>> 
Run Code Online (Sandbox Code Playgroud)