The python built in function filter
- 2020-06-03 06:59:42
- OfStack
The 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 in a custom or anonymous function is a Boolean. true preserves the value taken by the function and false takes the reverse.
iterator: Iterable objects.
Ex. :
Filter list ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']
As long as it contains the text string and takes it out or gets reversed.
s.rfind'text'+1
rfind() in Python3 returns the position of the last occurrence of the string, or -1 if there is no match.
In the number 0 is false, the integer above 0 is true, so s. rfind'text' will have +1, no characters found and -1+1=0.
# Filter
li = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']
# By default, the value fetched by the function is retained
print(list(filter(lambda s: s.rfind('text') + 1, li)))
# Take the next 3 An example is 1 The sample of
print(list(filter(lambda s: not s.rfind('text') + 1, li)))
# Noe custom function
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 nl
print(distinguish(l1))
# Two Custom higher-order functions
l2 = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']
def f(s):
return s.rfind('text') + 1
def distinguish(func, array):
nl = []
for s in array:
if func(s):
nl.append(s)
return nl
print(distinguish(f, l2))
# Three anonymous function
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 nl
print(distinguish(lambda s: s.rfind('text') + 1, l3))
Thank you for reading, I hope to help you, thank you for your support to this site!