的子我知道計數列表項的簡單事件一樣簡單:的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 = data.count(any('foo' in s for s in data))
print("d_count:", d_count)
但也產生:
d_count: 0
我想知道如何計算列表中的子串出現的每一次出現,謝謝。
你期望的結果 - 2或3(因爲‘富’在第一個字符串出現兩次)? –
相關:https://stackoverflow.com/questions/45719958/how-to-count-numbers-in-a-list-via-certain-rules/45720028#45720028 – bendl
@Błotosmętek好點。我期望'2'。 – theprowler