Home > Backend Development > Python Tutorial > Python learning tips: Examples of derivation and filtering operations on list items

Python learning tips: Examples of derivation and filtering operations on list items

黄舟
Release: 2017-05-21 13:51:51
Original
1422 people have browsed it

This article mainly introduces to you Python Learning tips related to the derivation and filtering operations of list items. The introduction in the article is very detailed and has certain reference learning value for everyone. It is necessary Friends, let’s take a look together.

This article introduces the relevant content about the derivation and filtering operations of list items in Python. It is shared for everyone’s reference and study. Let’s take a look 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)
Copy after login

Output 1:

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

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)
Copy after login

Output 2:

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

Application scenario

It is necessary to keep the original list unchanged and copy a new list data; only the data items of the compound conditions in the original list are copied.

Benefits

The copying and filtering operations are concentrated in one line, which reduces the indentation level of the code and makes the code more compact. Easier to read

OtherExplanation

1. The original data source may not be a list type, or it may be a tuple , generator and other iterable types

2. The built-in filter function can also achieve similar effects

3. in the itertools module The methods of ifilter and ifillterfalse can also achieve similar effects

4. If the amount of list data is huge, it needs to be used with caution and pay attention to memory consumption

Summary

The above is the detailed content of Python learning tips: Examples of derivation and filtering operations on list items. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template