簡體   English   中英

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

[英]Partial matching of strings in lists, python

我正在嘗試創建一些代碼來查看列表以查看哪些元素匹配,然后在新列表中返回這些元素。 我上面有一個 function 確定了 list_b 的兩個 colors。

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] 

在這個例子中我想要的 output 是......

["the red bird is fast", "the blue bird lives in the green tree"]

您可以使用列表理解:

list_c = [sentence for sentence in list_a if any(color in sentence for color in list_b)]

print(list_c)

Output:

['the red bird is fast', 'the blue bird lives in a green tree']

在此處閱讀有關列表理解的更多信息。

解決問題的一個簡單方法是使用嵌套循環和美妙的“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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM