This question already has an answer here:
这个问题在这里已有答案:
- Loop “Forgets” to Remove Some Items [duplicate] 10 answers
- How to remove items from a list while iterating? 26 answers
循环“忘记”删除一些项目[重复] 10个答案
迭代时如何从列表中删除项目? 26个答案
I would like to iterate over the elements of a list, and delete the wrong ones. First, lets check all elements:
我想迭代列表的元素,并删除错误的元素。首先,让我们检查所有元素:
tikzFiles=['keepme.tikz','inputs.tex','bla1.bat','bla2.tex','bla3.py']
for sFile in tikzFiles:
print(sFile)
print(sFile.endswith('.tikz'))
This leads to the expected result:
这导致了预期的结果:
keepme.tikz
True
inputs.tex
False
bla1.bat
False
bla2.tex
False
bla3.py
False
Two more lines, however,
还有两行,
for sFile in tikzFiles:
print(sFile)
print(sFile.endswith('.tikz'))
if not sFile.endswith('.tikz'):
tikzFiles.remove(sFile)
let the for-loop ignore the elements 'bla1.bat' and 'bla3.py':
让for-loop忽略元素'bla1.bat'和'bla3.py':
keepme.tikz
True
inputs.tex
False
bla2.tex
False
1 个解决方案
#1
Use list comprehension to create a new list with only the elements you want, like this
使用list comprehension创建一个只包含所需元素的新列表,如下所示
>>> tikzFiles = ['keepme.tikz', 'inputs.tex', 'bla1.bat', 'bla2.tex', 'bla3.py']
>>> [file for file in tikzFiles if file.endswith('.tikz')]
['keepme.tikz']
Note: More often, removing an element from a collection while you iterate it, is a bad idea. Check this answer to know more about what is actually going on at runtime.
注意:更常见的是,在迭代时从集合中删除元素是个坏主意。检查此答案以了解有关运行时实际运行情况的更多信息。
#1
Use list comprehension to create a new list with only the elements you want, like this
使用list comprehension创建一个只包含所需元素的新列表,如下所示
>>> tikzFiles = ['keepme.tikz', 'inputs.tex', 'bla1.bat', 'bla2.tex', 'bla3.py']
>>> [file for file in tikzFiles if file.endswith('.tikz')]
['keepme.tikz']
Note: More often, removing an element from a collection while you iterate it, is a bad idea. Check this answer to know more about what is actually going on at runtime.
注意:更常见的是,在迭代时从集合中删除元素是个坏主意。检查此答案以了解有关运行时实际运行情况的更多信息。