搜索字符串,使用列表元素进行匹配,返回找到的匹配项。

huangapple go评论98阅读模式
英文:

Search a string using list elements for matches and return the match found

问题

我试图在字符串中查找列表中的任何元素,并返回找到的匹配项。

我目前有以下代码:

  1. y = "test string"
  2. z = ["test", "banana", "example"]
  3. if any(x in y for x in z):
  4. match_found = x
  5. 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

  1. y = "test string"
  2. z = ["test", "banana", "example"]
  3. if any(x in y for x in z):
  4. match_found = x
  5. 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

以下是翻译好的部分:

  1. 我认为你正在寻找这个
  2. text = "测试字符串"
  3. words = ["测试", "香蕉", "示例"]
  4. found_words = [word for word in words if word in text]
  5. print(found_words)
  6. 结果
  7. ['测试']
英文:

I think you looking for this

  1. text = "test string"
  2. words = ["test", "banana", "example"]
  3. found_words = [word for word in words if word in text]
  4. print(found_words)

result

  1. ['test']

答案2

得分: 0

  1. 我认为你应该这样做:

res = [x for x in z if x in y]
print(f"匹配: {', '.join(res) if res else '无'}")

输出

匹配: test

  1. <details>
  2. <summary>英文:</summary>
  3. 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

  1. </details>
  2. # 答案3
  3. **得分**: 0
  4. 你可以执行以下操作:
  5. y = "测试字符串"
  6. z = ["测试", "香蕉", "示例"]
  7. for x in z:
  8. if x in y:
  9. match_found = x
  10. print("匹配项: " + match_found)
  11. break
  12. <details>
  13. <summary>英文:</summary>
  14. You can do the below:
  15. y = &quot;test string&quot;
  16. z = [&quot;test&quot;, &quot;banana&quot;, &quot;example&quot;]
  17. for x in z:
  18. if x in y:
  19. match_found = x
  20. print(&quot;Match: &quot; + match_found)
  21. break
  22. </details>
  23. # 答案4
  24. **得分**: 0
  25. 可以使用filter和lambda函数:
  26. ```python
  27. >>> list(filter(lambda x: x in y, z))
  28. ['test']
英文:

you can use filter and lambda function:

  1. &gt;&gt;&gt; list(filter(lambda x: x in y, z))
  2. [&#39;test&#39;]

huangapple
  • 本文由 发表于 2023年1月9日 03:54:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050828.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定