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.