Home  >  Article  >  Backend Development  >  Detailed explanation of the built-in function filter in Python

Detailed explanation of the built-in function filter in Python

黄舟
黄舟Original
2017-06-04 10:17:141420browse

This article mainly introduces python Built-in function filter related information, friends in need can refer to

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 in custom or anonymous function is a Boolean value, true will retain the value obtained by the function The value of false is inverted.
iterator: iterable object.

Example:

Filter list ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']
As long as it contains textStringand take it out or negate it.

s.rfind'text'+1

rfind() in Python3 returns the position of the last occurrence of the string, if there is no match Returns -1.
0 in numbers is false, and integers above 0 are all true, so there will be +1 after s.rfind'text', no character found and -1+1=0.

# 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)))
# 取反,下三个例子是一样的
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 High Order function

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))

The above is the detailed content of Detailed explanation of the built-in function filter in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn