[英]Given two lists of strings, find the total number of strings in the second list which contains any string in the first list as substring
ListA = ['are','stop','kill']
ListB = ['never','fullstop','nonstop','area','AreYou','stoppable','point']
我們在ListB
有兩個帶有子字符串“are”的字符串和三個帶有“stop”的字符串。 沒有'kill'。 所以答案是 5. 編輯:不區分大小寫的匹配
我們可以使用列表理解來做到這一點嗎?
這是一個簡單的方法,但我得到 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
這個:
>>> 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.