【问题标题】:Removing the current item I'm iterating over in a loop in Python 3.x删除我在 Python 3.x 中循环迭代的当前项目
【发布时间】:2021-05-12 14:38:18
【问题描述】:

我目前在 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)

我的目标是查看列表 file_list 中每个文件的内容。在查看内容时,我想检查列表 lst_exclusion_terms 中的任何条目是否存在。如果是这样,我想从列表中删除该条目。

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

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

有什么建议吗?谢谢

【问题讨论】:

  • 我有一个傻笑,你标记了你的问题[enumerate]enumerate() function 是您所需要的。请记住,您不想在迭代列表时从列表中删除项目(发生错误)。 stackoverflow.com/questions/1207406/…
  • 感谢@PranavHosangadi。我用谷歌搜索了一下,发现 enumerate 并认为它是相关的,但无法计算出代码。根据您提到的有关错误发生的评论,您建议的方法是什么?将索引号添加到临时列表中,然后通过此操作进行删除?
  • “您建议的方法是?”请参阅我之前评论中另一个 SO 问题的链接。
  • enumerate() 有什么问题吗?它的工作原理是这样的:for index, value in enumerate(my_collection)。不出所料,index 为您提供当前迭代中正在考虑的 my_collection 元素的索引,value 为您提供它的值。

标签: python python-3.x list enumerate


【解决方案1】:

你想filter一个文件列表,根据它们是否包含一些文本。

有一个 Python 内置函数 filter 可以做到这一点。 filter 采用一个函数,该函数返回一个布尔值和一个可迭代对象(例如列表),并返回一个迭代器,该迭代器对来自函数返回 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))

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2011-11-12
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 2020-04-26
      • 1970-01-01
      相关资源
      最近更新 更多