Home >Backend Development >Python Tutorial >How to filter elements in a sequence in Python
The content of this article is about how Python filters elements in a sequence. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Requirements
The sequence contains some data, we need to extract the values or delete the sequence according to certain standards,
2. Solution
To filter data in a sequence, usually the easiest way is to use a list comprehension.
For example:
myList=[1,4,-5,10,-7,2,3,-1] print([n for n in myList if n>0]) print([n for n in myList if n<0])
Result:
[1, 4, 10, 2, 3] [-5, -7, -1]
A potential disadvantage of using list comprehensions is that if the original input is very large, doing so may produce a huge the result of. If this is a problem you need to consider, you can use a generator expression to generate filtering results through an iterative method, for example:
myList=[1,4,-5,10,-7,2,3,-1] pos=(n for n in myList if n >0) for x in pos: print(x)
Result:
1 4 10 2 3
Sometimes the filtering criteria cannot be simple expressed in a list comprehension or generator expression. For example: Suppose the screening process involves exception handling or other complex details. Based on this, you can put the code that handles the filtering logic into a separate function, and then use the built-in filter() function to process it. The example is as follows:
values=['1','2','-3','-','4','N/A','5'] def is_int(val): try: x=int(val) return True except ValueError: return False ivals=list(filter(is_int,values)) print(ivals)
Result:
['1', '2', '-3', '4', '5']
filter() An iterator is created, so if we want the result as a list, make sure to include list(), like in the example.
3. Analysis
List comprehensions and generator expressions are usually the simplest and most direct way to filter data. In addition, they also have the ability to transform data simultaneously. For example:
import math myList=[1,4,-5,10,-7,2,3,-1] print([math.sqrt(n) for n in myList if n>0])
Result:
[1.0, 2.0, 3.1622776601683795, 1.4142135623730951, 1.7320508075688772]
Regarding filtering data, one situation is to replace values that do not meet the criteria with new values instead of discarding them. For example. In addition to finding positive integers, we also want to replace values that do not meet the requirements within a specified range. Often this can be easily accomplished by moving the filter criteria into a conditional expression, like this:
myList=[1,4,-5,10,-7,2,3,-1] print([n if n>0 else 0 for n in myList]) print([n if n<0 else 0 for n in myList])
Result:
[1, 4, 0, 10, 0, 2, 3, 0] [0, 0, -5, 0, -7, 0, 0, -1]
Another filtering tool worth mentioning is itertools .compress(), which accepts an iterable and a sequence of Boolean selectors as input. On output, it gives all iterable object elements that are True in the corresponding Boolean selector. This is useful if you want to apply the results of a filter on one sequence to another related sequence.
For example:
from itertools import compress address=[ '5412 N CLARK1', '5148 N CLARK2', '5800 E CLARK3', '2122 N CLARK4', '5645 M CLARK5', '1060 W CLARK6', ] counts=[0,3,10,4,1,7] #构建一个列表,它相应的count值要大于5 more5=[n>5 for n in counts] print(more5) print(list(compress(address,more5)))
Result:
[False, False, True, False, False, True] ['5800 E CLARK3', '1060 W CLARK6']
The key here is to first create a Boolean sequence to represent which element can meet our conditions, and then compress() function Select the corresponding elements whose Boolean value is True.
Same as the filter() function, compress() will return an iterator under normal circumstances. Therefore, if necessary, you have to use list() to convert the result into a list.
The above is the detailed content of How to filter elements in a sequence in Python. For more information, please follow other related articles on the PHP Chinese website!