计算字符串列表中子字符串的出现


问题内容

我知道对列表项的简单出现进行计数很容易:

>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3

但是我想知道的是每次在列表项的子字符串中出现一个字符串时都要计数。

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

data = ["the foo is all fooed", "the bar is all barred", "foo is now a bar"]

正在做:

d_count = data.count('foo')
print("d_count:", d_count)

产生:

d_count: 0

但我希望得到:

d_count: 2

我也尝试做:

d_count = data.count(any('foo' in s for s in data))
print("d_count:", d_count)

但结果也为零。

我想知道如何计算列表中子字符串出现的每次发生。


问题答案:

您可以使用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
>>>

该代码有效,因为布尔值可以视为整数。每次'foo'出现在字符串元素中,True均被返回。的整数值True1。就像每次'foo'都在一个字符串中一样,我们返回1。因此,对1返回的求和将得出1元素中出现的次数。

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

>>> sum(1 for s in data if 'foo' in s)
2
>>>