---
title: "python中的filter函数"
author: "lampeter123"
date: "2009-12-10T16:51:43Z"
tags: []
categories: ["编程语言"]
slug: "python-filter"
draft: false
lastmod: "2009-12-10T16:51:43Z"
id: 545658
url: "https://lampeter123.iteye.com/blog/545658"
---

filter函数，是用来过滤列表的。简单的说就是用一个函数来过滤一个列表，把列表的每一项传递进入过滤函数，过滤函数返回false就从这个列表中删除该项。

```
def add1(a):
    if a > 2:
        return True
    return False

a1 = [1,2,3,4,5]

b = filter(add1, a1)
print b
```

 

 

其实这个filter函数相当于这个：

```
c = [b for b in a1 if b > 2]
print c
```