Python-统计lis子字符串中字符串的出现次数

2024-05-19 18:48:49 发布

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

我知道,计算一个列表项的简单出现次数就像:

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

但我想知道的是,每当一个字符串出现在列表项的子字符串中时,该如何计数。

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

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 = data.count(any('foo' in s for s in data))
print("d_count:", d_count)

但这也产生了:

d_count: 0

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


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

你可以试试这个:

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

如果数据=[“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
>>> 

相关问题 更多 >