Python built-in function filter, python Function filter
Python built-in Function filter
class filter(object): """ filter(function or None, iterable) --> filter object Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true. """
Filter (func, iterator)
Func: the value obtained from a custom or anonymous function is a Boolean value. true indicates that the value obtained by the function is retained, and false indicates that the value is reversed.
Iterator: iteratable object.
Example:
Filter list ['text _ test_text ', 'test _ text_1', 'text _ test_2 ', '3 _ test_text', 'test _ test']
As long as the text string is contained and it is retrieved or reversed.
S. rfind 'text' + 1
Rfind () in Python3 returns the position of the last occurrence of the string. If no match exists,-1 is returned.
0 is false in the number, and an integer greater than 0 is true. Therefore, s. rfind 'text' is followed by + 1, and no characters and-1 + 1 = 0 are found.
# Filter
Li = ['text _ test_text ', 'test _ text_1', 'text _ test_2 ', '3 _ test_text ', 'test _ test'] # print (list (filter (lambda s: s. rfind ('text') + 1, li) # returns the result. The next three examples are the same print (list (filter (lambda s: not s. rfind ('text') + 1, li )))
# Noe User-Defined Functions
l1 = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']def distinguish(l): nl = [] for s in l: if s.rfind("text") + 1: nl.append(s) return nlprint(distinguish(l1))
# Two udfs
l2 = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']def f(s): return s.rfind('text') + 1def distinguish(func, array): nl = [] for s in array: if func(s): nl.append(s) return nlprint(distinguish(f, l2))
# Three anonymous Functions
l3 = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']def distinguish(func, array): nl = [] for s in array: if func(s): nl.append(s) return nlprint(distinguish(lambda s: s.rfind('text') + 1, l3))
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!