统计子字符串在字符串列表中的出现次数

2024-05-19 06:44:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道计算列表项的简单出现次数非常简单:

>>> [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)

但结果也是零

我想知道如何计算列表中出现的每个子字符串


Tags: the字符串in列表datafooiscount
3条回答

如果数据=[“abababa in foo”,“abababa”]

从列表中查找“aba”的发生情况, 您应该使用以下代码:

>>> data = ["abababa in foo", "abababa"]
>>> str = "aba"
>>> length = len(str)
>>> sum(element[index:index+length] == str for element in data for index,char in enumerate(element))
6

您可以通过使用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'出现在字符串元素中时,都会返回TrueTrue的整数值为1。这就好像每次'foo'在一个字符串中,我们都返回1。因此,对返回的1求和将得到1在元素中出现的次数

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

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

您可以尝试以下方法:

from itertools import chain

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

data = list(chain.from_iterable([i.split() for i in data]))

print(data.count("foo"))

输出:

2

相关问题 更多 >

    热门问题