It's like literally , Can be in place Retain Satisfied in an object Specify requirements The elements of .
for example , We want to get rid of list Medium Specify the number , Given an array A as follows :
A = [3, 7, 8, 6, 9, 8, 2, 1, 8]
Now we want to get rid of all the numbers 8. One of the easiest ways is, of course, to write for loop :
A = [3, 7, 8, 6, 9, 8, 2, 1, 8]
for a in A:
if a == 8:
A.remove(8)
print(A)
But such words are not very concise . utilize filter The function is written as follows :
A = [3, 7, 8, 6, 9, 8, 2, 1, 8]
def not_8(x):
return x != 8
A = filter(not_8, A)
print(list(A))
The decision conditions are encapsulated here for convenience of understanding , actually :
filter(not_8, A)
And anonymous function
filter(lambda x: x != 8, A)
Is the same , The latter is more common in real code .
summary , The formal syntax specification is as follows :
filter(function, iterable)