簡體   English   中英

遍歷列表並在其他列表中找不到時返回 none

[英]Iterate through list and return none if not found in other list

我正在嘗試遍歷我的列表“發送”。 如果我的另一個列表“food”包含列表“sents”中的一個元素,我想將列表“food”中的值附加到“result”,如果沒有,則不附加任何值。

到目前為止我所擁有的是:

result = []

sents = ['I love pizza. its my favorite', 'lets go get a sub', 'I just want a big fat steak']

food = ['sub', 'pizza', 'burger', 'noodles', 'candy']

我知道這應該很簡單,但我似乎無法弄清楚如何做到這一點。 我嘗試執行以下操作:

for x in sents:
    for z in food:
        if z in x:
            result.append(z)
        else:
            result.append("None")

但這顯然為 food 中的每個列表項附加了一個元素。

我試圖讓我的“結果”列表看起來像:

result = ['pizza', 'sub', 'none']

任何幫助將不勝感激。

您首先必須解析您的發送sents list並查找關鍵字( food )。 找到這些關鍵字后,您可以將它們附加到結果列表中。 這是我的觀點,來自另一種編程語言。 您必須將這個理論應用到 Python 中。 (我會評論但沒有足夠的聲望點)

你可以試試這個..

result = []

sents = ['I love pizza. its my favorite', 'lets go get a sub', 'I just want a big fat steak']

food = ['sub', 'pizza', 'burger', 'noodles', 'candy']

for lines in sents:
     flg = 0
     for items in food:
         if items in lines:
              result.append(items)
              flg=1
     if flg==0:
         result.append('None')

print(result)
# result = ['pizza', 'sub', 'none']
Result = list([x if sents.find(x) else 'none' for x in food])

#updated for string.find() #also,不考慮大小寫差異

暫無
暫無

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

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