[英]Filter list of strings to not contain any of the string from another list as a substring
[英]Two Lists of strings: remove strings from list A that contain any string from list B?
我有兩個字符串列表。
filters = ['foo', 'bar']
wordlist = ['hey', 'badge', 'foot', 'bar', 'cone']
我想刪除單詞列表中包含過濾器的每個單詞。
def filter_wordlist(filters, wordlist):
for word in wordlist:
if word contains any string from filters, remove it from the wordlist
return wordlist
因此,此過濾器函數將返回['hey', 'badge', 'cone']
。 它刪除了bar
因為bar
在filters
。 它刪除了foot
因為其中包含字符串foo
。
我嘗試了這個:
for word in wordlist:
for f in filters:
if f in word:
wordlist.remove(word)
但是它始終返回ValueError: list.remove(x): x not in list
。 因此,我嘗試將其包裝在一系列越來越令人沮喪的try / except塊中,但是在地鼠洞中沒有任何作用。 我在remove命令下添加了break
語句,但這很...參差不齊。 似乎wordlist
末尾的項目未正確過濾。
所以我改變了策略:
for f in filters:
for word in wordlist:
if f in word:
wordlist.remove(word)
就像以前一樣,這參差不齊。
所以我嘗試了這個:
for word in wordlist:
if any(f in word for f in filters):
wordlist.remove(word)
現在,這肯定讓我很惱火。 參差不齊。 到現在為止,我已經意識到發生了什么-在我遍歷列表時使用remove()
更改了列表,這搞砸了迭代。
這似乎應該很簡單。 我有兩個字符串列表。 取出列表A中的所有項目。如果這些項目中的任何一個包含列表B中的任何項目,請從列表A中刪除該項目。
這是我終於得到的有效解決方案:
keepitup = True
while keepitup:
start_length = len(wordlist)
for word in wordlist:
if any(f in word for f in filters):
wordlist.remove(link)
end_length = len(wordlist)
if start_length != end_length:
keepitup = True
else:
keepitup = False
這似乎很荒謬。 當然有更好的方法嗎?
您可以使用列表理解:
wordlist = [word for word in wordlist if all(f not in word for f in filters)]
或過濾功能:
filter(lambda word: all(f not in word for f in filters), wordlist)
或者您可以遍歷單詞表的副本:
for word in wordlist[:]:
if any(f in word for f in filters):
wordlist.remove(word)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.