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

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

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 = &quot;test string&quot;
    z = [&quot;test&quot;, &quot;banana&quot;, &quot;example&quot;]

    for x in z:
     if x in y:
      match_found = x
      print(&quot;Match: &quot; + 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:

&gt;&gt;&gt; list(filter(lambda x: x in y, z))
[&#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:

确定