problem: You have a data series that you want to use to extract the required values from or shorten the sequence
Answer
EG1: List derivation
The simplest way to filter sequence elements is to use list derivation. Like what:
>>> mylist = [1, 4,-5, 10,-7, 2, 3,-1]
>>> [n for N in mylist if n > 0]
[1, 4, 10, 2, 3]
>>> [n for N in MyList if n < 0]
[-5,-7,-1]
EG2: Generator expression iterations
a potential flaw in using list derivation is that it produces a very large result if the input is very large set, which consumes a lot of memory. If you are sensitive to memory, you can use the generator expression to iterate over the filtered elements. For example:
>>> pos = (n for n in mylist if n > 0)
>>> POS
<generator Object <genexpr> at 0x1006a0eb0>
>>> for x in POS:
... print (x)
...
1
4
10
2
3
Eg3:filter ()
Sometimes, filtering rules are complex and cannot be simply expressed in a list derivation or in a generator expression come on. For example, there are some exceptions or other complexities that need to be handled when filtering. You can put the filter code in a function, and then use the built-in filter () function
>>>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)
# Outputs [' 1 ', ' 2 ', '-3 ', ' 4 ', ' 5 ']
The filter () function creates an iterator, so if you want a list, it's like an example then use list () to convert.
Python: sequence: Filtering sequence elements