2017-08-17 76 views
0

的子我知道計數列表項的簡單事件一樣簡單:的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

我想知道如何計算列表中的子串出現的每一次出現,謝謝。

+3

你期望的結果 - 2或3(因爲‘富’在第一個字符串出現兩次)? –

+0

相關:https://stackoverflow.com/questions/45719958/how-to-count-numbers-in-a-list-via-certain-rules/45720028#45720028 – bendl

+0

@Błotosmętek好點。我期望'2'。 – theprowler

回答

5

您可以通過使用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'都出現在一個字符串元素中,則返回True。整數值True1。所以這就好像每次'foo'都在一個字符串中,我們返回1。因此,總計返回的1將產生出現在元素中的次數1

甲寫上面的代碼也許更明確的但等效的方式將是:

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

完美的工作,'sum'命令,非常感謝。我認爲會有一些簡單的命令可以解決這個問題,我根本不知道。 – theprowler

+0

很高興我可以幫忙@theprowler ;-) –

+0

最後一種方法看起來可疑。如果其中一個字符串以「fo」結尾而下一個字符以「o」開頭呢?它也會給其他方法帶來不同的結果,因爲它計算*所有*出現(並且它只能找到整個單詞而不僅僅是子串)。 – ekhumoro

1

你可以試試這個:

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 
0

如果數據= [ 「ABABABA在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 
相關問題