A small problem with the remove operation from the Python list

Source: Internet
Author: User
Tags python list

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.