【问题标题】:How check if my string has any word who contains an element [duplicate]如何检查我的字符串是否有任何包含元素的单词[重复]
【发布时间】:2021-09-10 17:59:39
【问题描述】:

我有一个清单:

my_list = ['hello', 'def-456', 'ghello', 'abc', 'helloajisjioj']

并且想要搜索包含字符串“hello”的项目。我该怎么做?

结果应该是: 'hello', 'ghello', 'helloajisjioj'

我该怎么做?我尝试了查找,但他只找到“你好”。

我试过类似的东西:

if 'hello' in my_list:

感谢您的回答。

【问题讨论】:

标签: python python-3.x


【解决方案1】:

这里是一个班轮

print([x for x in my_list if "hello" in x])

输出:

['hello', 'ghello', 'helloajisjioj']

【讨论】:

  • 谢谢,它的功能,但我不明白 de x for x in my_list?是双循环吗?
  • 这是列表理解。这意味着:a=[]for x in my_list:if hello in x: a.append(x)print(a)@guiguilecodeur
  • 指向文档更简单:docs.python.org/3/tutorial/….
  • 最欢迎@guiguilecodeur
【解决方案2】:

有很多方法可以做到这一点,但好处可能在于列表理解:

words_with_hello = [word for word in my_list if "hello" in word]

【讨论】:

    【解决方案3】:

    我们也可以使用filter

    >>> list(filter(lambda x: 'hello' in x, my_list))
    ['hello', 'ghello', 'helloajisjioj']
    

    【讨论】:

    • 很好的变化,但值得一提的是列表理解更快,更“pythonic”。
    • 好点。我只是想指出存在这样的功能。
    猜你喜欢
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 2012-08-31
    • 2016-02-24
    • 2022-06-14
    • 1970-01-01
    • 2015-03-14
    • 2011-12-23
    相关资源
    最近更新 更多