英文:
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循环?
英文:
I am trying to search a string for any elements in a list, and return the match found.
I currently have
y = "test string"
z = ["test", "banana", "example"]
if any(x in y for x in z):
match_found = x
print("Match: " + match_found)
This obviously does not work, but is there a good way to accomplish this besides using a for loop and an if loop?
答案1
得分: 0
以下是翻译好的部分:
我认为你正在寻找这个
text = "测试字符串"
words = ["测试", "香蕉", "示例"]
found_words = [word for word in words if word in text]
print(found_words)
结果
['测试']
英文:
I think you looking for this
text = "test string"
words = ["test", "banana", "example"]
found_words = [word for word in words if word in text]
print(found_words)
result
['test']
答案2
得分: 0
我认为你应该这样做:
res = [x for x in z if x in y]
print(f"匹配: {', '.join(res) if res else '无'}")
输出
匹配: test
<details>
<summary>英文:</summary>
I think you should do:
res = [x for x in z if x in y]
print(f"Match: {', '.join(res) if res else 'no'}")
Output
Match: test
</details>
# 答案3
**得分**: 0
你可以执行以下操作:
y = "测试字符串"
z = ["测试", "香蕉", "示例"]
for x in z:
if x in y:
match_found = x
print("匹配项: " + match_found)
break
<details>
<summary>英文:</summary>
You can do the below:
y = "test string"
z = ["test", "banana", "example"]
for x in z:
if x in y:
match_found = x
print("Match: " + match_found)
break
</details>
# 答案4
**得分**: 0
可以使用filter和lambda函数:
```python
>>> list(filter(lambda x: x in y, z))
['test']
英文:
you can use filter and lambda function:
>>> list(filter(lambda x: x in y, z))
['test']
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论