开发者

Why are certain elements of this python list ignored?

I'm new to Python, and i'm struggling to understand the output of this simple program:

list = os.listdir(os.getcwd())
print(list)
print()
for element in list:
    print(element)
    if 'txt' not in element: list.remove(element)

Which gives me this output :

['examples_list.txt', 'gener开发者_运维技巧ate_patterns.py', 'lehoczky_example_3.txt', 'patterns', 'test.py', 'test2.py']

examples_list.txt
generate_patterns.py
patterns
test2.py

why are certain elements (such as 'lehoczky_example_3.txt'), ignored by the "for" loop?


You cannot remove elements from the list while looping through it. Try and loop over a copy of the list, or create a new one with only the elements you want to keep.

See also Python strange behavior in for loop or lists


Try list comprehension. This will keep your list of files and create a new list noTxtFiles without touching the files.

files = os.listdir(os.getcwd())
noTxtFiles = [ element for element in files if 'txt' not in element ]

And don't use the reserved word list for a variable name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜