【Python学习之五】高级特性3(切片、迭代、列表生成器、生成器、迭代器)

3、列表生成器(List Comprehensions)

  列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。举个例子,要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11))

>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  还有一种常用的简洁的方法:

>>> [x * x for x in range(1, 11)]             #x * x表示要生成的元素
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 

for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方:

>>> L = [x * x for x in range(1, 11) if x % 2 == 0]
>>> L
[4, 16, 36, 64, 100]

  代码练习:

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Date    : 2018-05-22 21:25:01
 4 # @Author  : Chen Jing (cjvaely@foxmail.com)
 5 # @Link    : https://github.com/Cjvaely
 6 # @Version : $Id$
 7 
 8 # 列表生成式练习
 9 
10 # 请修改列表生成式,通过添加if语句保证列表生成式能正确地执行:
11 
12 L1 = ['Hello', 'World', 18, 'Apple', None]
13 L2 = []
14 for x in L1:
15     if isinstance(x, str):
16         L2.append(x)
17 L2 = [s.lower() for s in L2]
18 # 测试:
19 print(L2)
20 if L2 == ['hello', 'world', 'apple']:
21     print('测试通过!')
22 else:
23     print('测试失败!')
原文地址:https://www.cnblogs.com/cjvae/p/9318389.html