从缺少特定字符串的列表中删除元素-python

从缺少特定字符串的列表中删除元素-python,python,list,elements,Python,List,Elements,我有一个很大的列表,看起来像这样: entries = ["['stuff']...other stuff", "['stuff']...stuff", "['stuff']...more stuff", ...] 我想删除列表中所有不包含单词“other”或“things”的元素 我尝试了这一点,但它并没有删除我需要的所有元素(只有接近结尾的部分): 我做错了什么?您不应该在迭代列表时从列表中删除项目。此外,您的条件语句并不能实现您的意思:它检查'other'的真实性,而只检查'things

我有一个很大的列表,看起来像这样:

entries = ["['stuff']...other stuff", "['stuff']...stuff", "['stuff']...more stuff", ...]
我想删除列表中所有不包含单词“other”“things”的元素

我尝试了这一点,但它并没有删除我需要的所有元素(只有接近结尾的部分):


我做错了什么?

您不应该在迭代列表时从列表中删除项目。此外,您的条件语句并不能实现您的意思:它检查
'other'
的真实性,而只检查
'things'
的包含性。要修复它,请在检查中使用两个单独的
,然后使用

如果列表不是很大,您可以使用列表理解来重建它:

entries = [e for e in entries if "other" not in e and "things" not in e]
否则,从列表的末尾循环到开头,并按索引删除项

for i in range(len(entries)-1, -1, -1):
    if "other" in entries[i] and "things" in entries[i]:
        del entries[i]

正如其他人已经指出的,在您的版本中存在三个主要问题:

for e in entries:
    if 'other' or 'things' not in e: #or returns first truthy value, and `if other` is always true.  Also, you need and, not or.
        entries.remove(e) #mutating the item you are iterating over is bad
print entries
for e in words[:]: #words[:] is a copy of words, solves mutation issue while iterating
    if 'other' not in e and 'things' not in e: #want words that both don't contain 'other' AND dont contain 'things'
        print(e)
        words.remove(e)
print(words)
这是您的版本,已修订以修复上述问题:

for e in entries:
    if 'other' or 'things' not in e: #or returns first truthy value, and `if other` is always true.  Also, you need and, not or.
        entries.remove(e) #mutating the item you are iterating over is bad
print entries
for e in words[:]: #words[:] is a copy of words, solves mutation issue while iterating
    if 'other' not in e and 'things' not in e: #want words that both don't contain 'other' AND dont contain 'things'
        print(e)
        words.remove(e)
print(words)
以下是一些替代方法:

import re

words = ['this doesnt contain chars you want so gone',
         'this contains other so will be included',
         'this is included bc stuff']

answer = list(filter(lambda x: re.search('other|stuff',x),words))
other_way = [sentence for sentence in words if re.search('other|stuff',sentence)]

print(answer)
print(other_way)
您可以使用列表理解表达式使用
all(…)
检查子字符串,如下所示:

>>> [entry for entry in entries if any(something in entry  for something in  ["other", "things"])]

这将返回包含“其他”或“事物”的新单词列表。

嗯,这两个词都是相当大的问题。但问题的近端原因是有条件的。紧随其后的是在迭代过程中对列表的修改。为了记录在案,我没有否决……还有,请注意,这将是你的下一个bug……谁重新打开了这个?这显然是重复的我没有投反对票,但这个答案质量很差。它只是提供了一个替代方法,没有解释为什么原始方法是错误的,或者您的替代方法实际上是如何工作的,如果问题是关于基本条件的,那么这将不会有很大帮助。