iter.md 1.3 KB
Newer Older
1 2
# Python 生成器推导式

F
feilong 已提交
3
Python 独步天下的推导式表达式,使用元表推导式过滤长度小于等于4的书籍
4 5

```python
F
feilong 已提交
6
# -*- coding: UTF-8 -*-
7
def test():
F
feilong 已提交
8
    books = ('程序员修炼之道', '构建之法', '代码大全', 'TCP/IP协议详解')
9

F
feilong 已提交
10
    # TODO(you): 此处请为reading进行正确的赋值
11

F
feilong 已提交
12 13 14
    print("太长的书就不看了,只读短的:")
    for book in reading:
        print(" ->《{}》".format(book))
15

F
feilong 已提交
16
    print("可是发现书的名字短,内容也可能很长啊!")
17 18 19


if __name__ == '__main__':
F
feilong 已提交
20
    test()
21 22 23 24
```

请选出下列能**正确**实现这一功能的选项。

25 26 27 28
## template

```python
def test():
F
feilong 已提交
29
    books = ('程序员修炼之道', '构建之法', '代码大全', 'TCP/IP协议详解')
30

F
feilong 已提交
31
    reading = (book for book in books if len(book) <= 4)
32

F
feilong 已提交
33 34 35
    print("太长的书就不看了,只读短的:")
    for book in reading:
        print(" ->《{}》".format(book))
36

F
feilong 已提交
37
    print("可是发现书的名字短,内容也可能很长啊!")
38 39 40


if __name__ == '__main__':
F
feilong 已提交
41
    test()
42 43 44 45
```



46 47 48
## 答案

```python
49
reading = (book for book in books if len(book) <= 4)
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
```



## 选项

### A

```python
reading = (books[i] for book in books: if len(book) < 4)
```

### B

```python
reading = (book for book in books if len(book) < 4)
```

### C

```python
reading = (book for book in books: if len(book) <= 4)
```