我正在尝试创建一些代码,这些代码将在列表中查找哪些元素具有匹配项,然后在新列表中返回这些元素。我有一个上面的函数来确定list_b的两种颜色。
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] 在这个例子中,我想要的输出是...
["the red bird is fast", "the blue bird lives in the green tree"]发布于 2021-06-11 01:06:04
您可以使用列表理解:
list_c = [sentence for sentence in list_a if any(color in sentence for color in list_b)]
print(list_c)输出:
['the red bird is fast', 'the blue bird lives in a green tree']阅读有关列表理解here的更多信息。
发布于 2021-06-11 01:04:33
解决问题的一个简单方法是使用嵌套循环和奇妙的"in“关键字。
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)https://stackoverflow.com/questions/67925452
复制相似问题