Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何在遍历列表时从列表中删除元素,而不跳过未来的迭代_Python_List_Loops_Iterable - Fatal编程技术网

Python:如何在遍历列表时从列表中删除元素,而不跳过未来的迭代

Python:如何在遍历列表时从列表中删除元素,而不跳过未来的迭代,python,list,loops,iterable,Python,List,Loops,Iterable,在python中,我注意到如果我在y中的x中用遍历一个列表,并在循环中删除y元素,最后一个元素将被“跳过”-我假设这是因为len(y)已更改 我试图抓取所有具有特定扩展名的文件,除了那些满足某些条件的文件 以下是原始代码: def test_print_numTXTs(fileList): counter = 0 for file in fileList: if file.name[-4:] == ".txt": cou

在python中,我注意到如果我在y中的x中用
遍历一个列表,并在循环中删除
y
元素,最后一个元素将被“跳过”-我假设这是因为
len(y)
已更改

我试图抓取所有具有特定扩展名的文件,除了那些满足某些条件的文件

以下是原始代码:

def test_print_numTXTs(fileList):
    counter = 0
    for file in fileList:
        if file.name[-4:] == ".txt":
            counter +=1
            if file.name == "a.txt":
                fileList.remove(file)   #problem caused here
    print(counter)
    print(len(fileList))
计数器的输出比.txt文件总数少一个。通过调试程序,我可以看到它跳过了循环的最后一次迭代(我假设是因为
len(fileList)
现在
-=1
w.r.t。它的初始
len()

下面的代码“有效”,但感觉像是一个黑客-我将要从列表中删除的文件添加到第二个列表中,然后在事实发生后对其进行迭代。我注释掉了我原来的行,这导致了迭代的“跳过”

此代码输出所有.txt文件的计数,并且列表的长度比该值小一个(因为元素a.txt已被删除)-这是所需的行为


这个问题有更优雅的解决方案吗?

你是对的。你需要一个额外的列表。但是有一个更简单的解决方案

def print\u numxts(文件列表):
计数器=0
对于列表中的文件(文件列表):
如果file.name[-4::][=”.txt::
计数器+=1
如果file.name==“a.txt”:
文件列表。删除(文件)
秘密是“list(fileList)”。您可以创建一个额外的列表,并对其进行迭代

列表压缩功能同样强大。在您的示例中,它应该是这样工作的。我现在没有尝试过……只是在这里快速编写了

fileList=[如果file.name,则文件列表中的文件对应文件!=“a.txt”]

我不得不忽略最后一个循环:

def test\u print\u numTXTs(文件列表):
计数器=0
res=[]
对于文件列表中的文件:
如果file.name[-4::][=”.txt::
计数器+=1
如果file.name!=“a.txt”:
res.append(file)#此处导致的问题
打印(res)

这个解决方案是有效的。我会考虑它们是否是一种更具python风格的方式。

与手动筛选以
.txt
结尾的文件不同,您可以选择匹配此模式的文件

假设文件夹
foo
包含以下文件:

a.txt  
b.txt  
c.txt 
您要计算
*.txt
文件的数量,除了
a.txt

>>> from pathlib import Path
>>> file_list = Path('foo').glob('*.txt')
>>> sum(1 for f in file_list if f.name.endswith('.txt') and f.name != 'a.txt')
2

fileList=[f表示文件列表中的f,如果f!='a.txt']
…!?
>>> from pathlib import Path
>>> file_list = Path('foo').glob('*.txt')
>>> sum(1 for f in file_list if f.name.endswith('.txt') and f.name != 'a.txt')
2