在Python3.x中删除我在循环中迭代的当前项

2024-06-16 10:40:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前在Python 3.x中有以下代码:-

lst_exclusion_terms = ['bob','jenny', 'michael']
file_list = ['1.txt', '2.txt', '3.txt']

for f in file_list:
    with open(f, "r", encoding="utf-8") as file:
        content = file.read()
        if any(entry in content for entry in lst_exclusion_terms):
            print(content)

我的目标是查看列表文件列表中每个文件的内容。在查看内容时,我想检查列表中是否存在lst_排除项。如果有,我想从列表中删除该条目

因此,如果“bob”在2.txt的内容中,它将从列表中删除(弹出)

我不确定如何用命令替换我的print(content),以标识正在检查的项目的当前索引号,然后将其删除

有什么建议吗?谢谢


Tags: 文件intxt内容列表forcontentlist
2条回答

我以前有过这样的愿望,在迭代时需要删除列表项。通常建议只重新创建一个包含所需内容的新列表here

但是,以下是一种快速而肮脏的方法,可以从列表中删除该文件:

lst_exclusion_terms = ['bob','jenny', 'michael']
file_list = ['1.txt', '2.txt', '3.txt']
print("Before removing item:")
print(file_list)

flag = True
while flag:
    for i,f in enumerate(file_list):
        with open(f, "r", encoding="utf-8") as file:
            content = file.read()
        if any(entry in content for entry in lst_exclusion_terms):
            file_list.pop(i)
            flag = False
            break

print("After removing item")
print(file_list)

在本例中,文件3.txt已从列表中删除,因为它与lst_exclusion_terms匹配

以下是每个文件中使用的内容:

#1.txt
abcd
#2.txt
5/12/2021
#3.txt
bob
jenny
michael

您想根据文件是否包含某些文本来创建文件列表

有一个Python内置函数^{}可以做到这一点filter接受一个返回布尔值和iterable(例如列表)的函数,并返回一个迭代器,该迭代器遍历函数返回的原始iterable中的元素True

因此,首先您可以编写该函数:

def contains_terms(filepath, terms):
    with open(filepath) as f:
        content = f.read()
    return any(term in content for term in terms)
        

然后在filter中使用它,并根据结果构造一个list

file_list = list(filter(lambda f: not contains_terms(f, lst_exclusion_terms), file_list))

当然,lambda是必需的,因为contains_terms接受2个参数,如果术语在文件中,则返回True,这在某种程度上与您想要的相反(但从函数本身的角度来看,排序更有意义)。您可以根据您的用例专门化该函数,并消除对lambda的需要

def is_included(filepath):
    with open(filepath) as f:
        content = f.read()
    return all(term not in content for term in lst_exclusion_terms)

定义此函数后,对filter的调用更加简洁:

file_list = list(filter(is_included, file_list))

相关问题 更多 >