Python learning tips-derivation and filtering of list items, python list items

Source: Internet
Author: User
Tags python list

Python learning tips-derivation and filtering of list items, python list items

This article describes the derivation of list items in Python and the content related to filter operations. Share the content for your reference. Let's take a look at it below:

Typical code 1:

data_list = [1, 2, 3, 4, 0, -1, -2, 6, 8, -9] data_list_copy = [item for item in data_list]  print(data_list) print(data_list_copy) 

Output 1:

[1, 2, 3, 4, 0, -1, -2, 6, 8, -9] [1, 2, 3, 4, 0, -1, -2, 6, 8, -9] 

Typical Code 2:

data_list = [1, 2, 3, 4, 0, -1, -2, 6, 8, -9] data_list_copy = [item for item in data_list if item > 0]  print(data_list) print(data_list_copy) 

Output 2:

[1, 2, 3, 4, 0, -1, -2, 6, 8, -9] [1, 2, 3, 4, 6, 8] 

Application scenarios

To keep the original list unchanged, You need to copy a new list data, and only copy the data items with compound conditions in the original list.

Benefits

Copy and filter operations are concentrated in one row, reducing the code indentation level, making the code more compact and easier to read

Other Instructions

1. The original data source can not be a list type, or any iteratable type, such as tuples or generators.

2. the built-in filter function can achieve similar results.

3. The ifilter and ifilterfalse methods in the itertools module can achieve similar results.

4. Exercise caution when using the list with a large amount of data. Pay attention to memory consumption.

Summary

Well, the above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, you can leave a message, thank you for your support.

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.