首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >列表中字符串的部分匹配,python

列表中字符串的部分匹配,python
EN

Stack Overflow用户
提问于 2021-06-11 00:52:08
回答 2查看 45关注 0票数 1

我正在尝试创建一些代码,这些代码将在列表中查找哪些元素具有匹配项,然后在新列表中返回这些元素。我有一个上面的函数来确定list_b的两种颜色。

代码语言:javascript
复制
list_a = ["the red bird is fast", "the blue bird lives in a green tree", "the yellow bird is very angry"]

list_b = ["red", "green"]

list_c = [lambda x: x in list_b, list_a] 

在这个例子中,我想要的输出是...

代码语言:javascript
复制
["the red bird is fast", "the blue bird lives in the green tree"]
EN

回答 2

Stack Overflow用户

发布于 2021-06-11 01:06:04

您可以使用列表理解:

代码语言:javascript
复制
list_c = [sentence for sentence in list_a if any(color in sentence for color in list_b)]

print(list_c)

输出:

代码语言:javascript
复制
['the red bird is fast', 'the blue bird lives in a green tree']

阅读有关列表理解here的更多信息。

票数 1
EN

Stack Overflow用户

发布于 2021-06-11 01:04:33

解决问题的一个简单方法是使用嵌套循环和奇妙的"in“关键字。

代码语言:javascript
复制
list_a = ["the red bird is fast", "the blue bird lives in a green tree", "the yellow bird is very angry"]
list_b = ["red", "green"]
list_c = []

for color in list_b:
    for sentence in list_a:
        if color in sentence:
            list_c.append(sentence)

print(list_c)
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67925452

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档