我试图在列表中搜索任何元素的字符串,并返回找到的匹配。
我现在有
y = "test string"
z = ["test", "banana", "example"]
if any(x in y for x in z):
match_found = x
print("Match: " + match_found)
这显然不起作用,但是除了使用for循环和if循环之外,还有什么好的方法来完成这个任务吗?
我想你在找这个
text = "test string"
words = ["test", "banana", "example"]
found_words = [word for word in words if word in text]
print(found_words)
结果
['test']
我认为你应该这样做:
res = [x for x in z if x in y]
print(f"Match: {', '.join(res) if res else 'no'}")
# Output
Match: test
您可以这样做:
y = "test string"
z = ["test", "banana", "example"]
for x in z:
if x in y:
match_found = x
print("Match: " + match_found)
break
可以使用filter和lambda函数:
>>> list(filter(lambda x: x in y, z))
['test']