假設我有一個關鍵詞列表:terms = ["dog","cat","fish"]我還有另一個列表,其中包含更長的文本字符串:texts = ["I like my dog", "Hello world", "Random text"]我現在想要我有一個代碼,它基本上遍歷列表texts并檢查它是否包含列表中的任何項目terms,并且它應該返回一個列表,其中包含文本中的此項是否匹配。這是代碼應該產生的:result = ["match","no match","no match"]
1 回答

夢里花落0921
TA貢獻1772條經驗 獲得超6個贊
以下是如何使用zip()和列表理解:
terms = ["dog","cat","fish"]
texts = ["I like my dog", "Hello world", "Random text"]
results = ["match" if a in b else "no match" for a,b in zip(terms,texts)]
print(results)
輸出:
['match', 'no match', 'no match']
更新:結果證明壓縮不是 OP 想要的。
terms = ["dog","cat","fish"]
texts = ["I like my dog", "Hello world", "Random text"]
results = ["match" if any(b in a for b in terms) else "no match" for a in texts]
print(results)
輸出:
['match', 'no match', 'no match']
添加回答
舉報
0/150
提交
取消