A. Question:
Two days ago because of job needs, wrote a Python applet, a directory under all the length of less than 19 folders, such as this directory:
After filtering is complete, only the remaining "2014_11_03-12-11-23", "2014_11_04-13-11-26" folders can be left.
The procedure is as follows:
Cwdlist = Os.listdir ("E:\Python") for I in Cwdlist: If Len (i) <>: cwdlist.remove (i) Print cwdlist
But the results were counterproductive and the results were as follows:
Why is the "237" folder not erased?
Looked up on the internet, the original problem is on the list operation of the Remove method, the Remove method deletes the first occurrence of the element.
That is, it is queried by the element, and the first match it encounters is deleted. More importantly: the deleted element position will be filled by the following element.
That is, the program after the deletion of "236", this position by the back of the "237" to fill up, this moment,
The subscript of the list has been moved to the last element "237", after deleting "237", the entire loop ends.
Two. Workaround:
1. The simplest method, then copy a list to operate:
Cwdlist = Os.listdir ("E:\Python") Cwdlist2 = List (cwdlist) for I in Cwdlist2: If Len (i) <>: Cwdlist.remove (i) Print cwdlist
2. Use the filter function:
Cwdlist = Os.listdir ("E:\Python") def f (x): Return len (x) = = 19print Filter (f,cwdlist)
3. Use a lambda expression for a little more concise notation:
Cwdlist = Os.listdir ("E:\Python") F=lambda x:len (x) = = 19print Filter (f,cwdlist)
or
Cwdlist = Os.listdir ("E:\Python") print filter (lambda x:len (x) = = 19,cwdlist)
4. A more pythonic approach, using a list derivation:
Cwdlist = Os.listdir ("E:\Python") print [i-I in cwdlist if Len (i) = = 19]
In fact, the essence of these methods is the same, is a new list.
A small problem with the remove operation from the Python list