Python learns how to derive list items and filter them

  • 2020-06-01 10:13:12
  • OfStack

This article introduces the derivation and filtering operation of list items in Python, which is Shared for your reference and learning. Let's take a look at the following:

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

Need to keep the original list unchanged, need to copy 1 new list data; Copy only the data items in the original list with compound conditions.

The benefits

Copy and filter operations are concentrated in one line, reducing the level of indentation and making the code more compact and readable

Other instructions

1. The original data source may not be a list type, or it may be any iterable type such as tuples, generators, etc

2. The built-in filter function can achieve a similar effect

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

4. If there is a large amount of list data, use it carefully and pay attention to the memory consumption

conclusion


Related articles: