---
title: "Python filter sorted"
author: "fairy_xzc"
date: "2016-10-13T13:49:30Z"
tags: []
categories: ["编程语言"]
slug: "python-filter-sorted"
draft: false
lastmod: "2016-10-13T13:51:07Z"
id: 2330331
url: "https://agilestyle.iteye.com/blog/2330331"
---

**原创转载请注明出处：[http://agilestyle.iteye.com/blog/2330331](/blog/2330331)**

 

### Python内置的filter()函数用于过滤序列

过滤偶数

```
def is_odd(n):
    return n % 2 == 1


# [1, 3, 5, 7, 9]
print(list(filter(is_odd, list(range(1, 10)))))
```

过滤空字符串

```
def not_empty(s):
    return s and s.strip()


# ['a', 'b']
print(list(filter(not_empty, ['a', 'b', '', None])))
```

Console Output

![](http://dl2.iteye.com/upload/attachment/0120/5921/142d2767-fce5-372e-9d25-26aee1361e39.png)  
 

用filter求30以内的素数

```
def odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n


def not_divisible(n):
    return lambda x: x % n > 0


def primes():
    yield 2
    it = odd_iter()
    while True:
        n = next(it)
        yield n
        it = filter(not_divisible(n), it)


for i in primes():
    if i < 30:
        print(i)
    else:
        break
```

Console Output

![](http://dl2.iteye.com/upload/attachment/0120/5923/7aabaa7c-bcac-39ea-9bfd-4da6400a8bf5.png)  
 

### Python内置的sorted()函数就可以对list进行排序

```
# [-55, -44, 22, 33, 66, 77, 88]
print(sorted([88, 77, 66, -55, -44, 33, 22]))
# [22, 33, -44, -55, 66, 77, 88]
print(sorted([88, 77, 66, -55, -44, 33, 22], key=abs))
# ['HBase', 'HDFS', 'Hadoop', 'Hive', 'MapReduce']
print(sorted(['Hadoop', 'HDFS', 'MapReduce', 'Hive', 'HBase']))
# ['Hadoop', 'HBase', 'HDFS', 'Hive', 'MapReduce']
print(sorted(['Hadoop', 'HDFS', 'MapReduce', 'Hive', 'HBase'], key=str.lower))
# ['MapReduce', 'Hive', 'HDFS', 'HBase', 'Hadoop']
print(sorted(['Hadoop', 'HDFS', 'MapReduce', 'Hive', 'HBase'], key=str.lower, reverse=True))
```

Console Output

![](http://dl2.iteye.com/upload/attachment/0120/5925/604011a1-e4e9-3113-8a47-a6b0544fb084.png)