Filter
Filter () receives a function and a sequence
Unlike map (), filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is TRUE or False
In a list, delete the even number, leaving only the odd number:
def is_odd (n):
return n% 2 = = 1
List (filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
Sorted
The python built-in sorted () function can sort the list:
>>> Sorted ([36, 5,-12, 9,-21])
[-21,-12, 5, 9, 36]
The sorted () function is also a high-order function, and it can also receive a key function to implement a custom sort, such as by absolute size:
>>> sorted ([5, -12, 9, -21], key=abs)
[5, 9,-12,-21, 36]
Use a key function to map a string to ignore case ordering
Reverse sort, without changing the key function, you can pass in the third parameter reverse=true:
>>> sorted ([' Bob ', ' about ', ' Zoo ', ' credits '], Key=str.lower, reverse=true)
[' Zoo ', ' credits ', ' Bob ', ' about ']
Key also accepts a function, which accepts only one element
Reverse: Sorting rules. Reverse = True descending or reverse = False Ascending
Python filter&sorted