【发布时间】:2020-06-12 21:17:43
【问题描述】:
我知道计算列表项的简单出现次数很简单:
>>> [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)
但结果也是零。
我想知道如何计算列表中出现的每个子字符串。
【问题讨论】:
-
你期望什么结果——2或3(因为“foo”在第一个字符串中出现了两次)?
-
@Błotosmętek 好点。我希望
2。
标签: python