程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Simple understanding and usage of Python filter() function

編輯:Python

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)
  • iterable: Can be iterated ( By for loop ) The object of , The most common is the list
  • function: The decision function , When iterable When the element in is passed in , Return to True Is reserved , Otherwise, it is not reserved

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved