2015-11-05 14 views
-5
ListA = ['are','stop','kill'] 
ListB = ['never','fullstop','nonstop','area','AreYou','stoppable','point'] 

第二列表總數我們在ListB兩個字符串子串「是」三有「停止」。沒有'殺死'。所以答案是5.編輯:不區分大小寫的匹配字符串給定兩個列表,找到字符串,其中包含在第一列表中的任何字符串作爲子

我們可以使用列表理解嗎?

+1

如果'ListB'有一個字符串''stopkill''你會數一次還是兩次? –

+0

@StevenRumbalski只有一次.. – sinisteraadi

回答

1

這是一個簡單的方法,但我得到4:

>>> sum(a in b for a in ListA for b in ListB) 
4 

除非你想不區分大小寫

>>> sum(a.lower() in b.lower() for a in ListA for b in ListB) 
5 

如前所述,雖然,你的問題是不明確的:這種方法計數有多少匹配有。如果要算ListB有多少比賽,你可以這樣做:

>>> len(set(b for a in ListA for b in ListB if a.lower() in b.lower())) 
5 

由於它不同的例子:

>>> ListA = ['stop', 'kill'] 
>>> ListB = ['stoppable', 'killable', 'stopkill'] 

>>> sum(a.lower() in b.lower() for a in ListA for b in ListB) 
4 
>>> len(set(b for a in ListA for b in ListB if a.lower() in b.lower())) 
3 
+0

我想我的意思是多少場比賽。不太知道如何設計它。謝謝 – sinisteraadi

0

這樣的:

>>> ListA = ['are','stop','kill'] 
>>> ListB = ['never','fullstop','nonstop','area','AreYou','stoppable','point'] 
>>> len([b for b in ListB if any(filter(lambda a: a in b.lower(), ListA))]) 
5 
相關問題