![](/img/trans.png)
[英]Iterate two or more lists / numpy arrays… and compare each item with each other and avoid loops in python
[英]iterate and compare two lists in python, if contains string from the other list, pop item
我正在嘗試比較兩個列表(顯示代碼中的mama
和filterkeywords
),並根據第二個列表從第一個列表中刪除值。 我有這個代碼:
occurenceList = []
title = ['SL C ','FS D ','FS H','FS F','FS D','SL C','SL F','FS H','SL H','SL D']
mama = ['slow cat Sas','fast dog PoP','fast hen Luke','fast fish Lee','fast dog joe','slow cat yan','slow fish ben','Fast hen Tim','Slow hen Jen','slow dog moe']
filterkeywords = ['hen','dog','fish','Fish']
print(" ")
for text in mama:
for words in filterkeywords:
if words in text:
animal = (mama.index(text))
print("index: ", animal, ' | ', mama[animal], " | Word Found: ", words)
title.pop(animal)
mama.pop(animal)
print(" ")
for items in title:
itemindex = title.index(items)
print(itemindex, " ", items,' ',mama[itemindex])
這給出了這個 output:
index: 1 | fast dog PoP | Word Found: dog
index: 2 | fast fish Lee | Word Found: fish
index: 4 | slow fish ben | Word Found: fish
index: 5 | Slow hen Jen | Word Found: hen
0 SL C slow cat Sas
1 FS H fast hen Luke
2 FS D fast dog joe
3 SL C slow cat yan
1 FS H fast hen Luke
5 SL D slow dog moe
嵌套的 for 循環似乎只找到了一些匹配項,並且沒有按預期輸出。 為什么會這樣? 從mama
中刪除包含任何filterkeywords
的每個項目的最佳方法是什么?
這是一個非常直接的地方,可以使用列表推導生成不包含任何這些關鍵字的項目列表。
>>> [f"{i} {t} {m}" for i, (t, m) in enumerate(zip(title, mama))
... if not any(w in m for w in filterkeywords)]
['0 SL C slow cat Sas', '5 SL C slow cat yan']
>>>
傳遞給any
的生成器表達式會檢查是否存在任何關鍵字。 我們使用zip
來組合mama
中的標題和元素。 並enumerate
提供索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.