gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:23:07 26 4
gpt4 key购买 nike

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

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

此代码有效,因为 bool 值可以被视为整数。每次 'foo' 出现在字符串元素中时,返回 TrueTrue 的整数值为 1。所以就好像每次 'foo' 在字符串中时,我们都返回 1。因此,对返回的 1 求和将得出 1 在元素中出现的次数。

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

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

关于python - 计算字符串列表中子字符串的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45738789/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com