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)
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 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!