![](/img/trans.png)
[英]Search list of string elements that match another list of string elements
[英]Search a string using list elements for matches and return the match found
我正在尝试在字符串中搜索列表中的任何元素,并返回找到的匹配项。
我目前有
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
您可以使用过滤器和 lambda function:
>>> list(filter(lambda x: x in y, z))
['test']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.