列表推导式:
作用:用简易方法生成列表
语法:
[表达式 for 变量 in 可迭代对象] 或者 [表达式 for 变量 in 可迭代对象 if 真值表达式]
1、生成下列列表:
[1, 4, 9, 16, 25, .... 81]
>>> F = [ ]
>>> for x in range(1, 10):
... F.append(x ** 2)
...
>>> F
[1, 4, 9, 16, 25, 36, 49, 64, 81]
列表推到式生成
>>>F = [x ** 2 for x in range(1, 10)]
结果
>>> F
[1, 4, 9, 16, 25, 36, 49, 64, 81]
2、生成1~100内奇数的列表
>>> F = [ ]
>>> for x in range(1, 100):
... if x % 2 == 1:
... F.append(x)
>>>
列表式生成
>>>F = [x for x in range(1, 100) if x % 2 == 1]
结果
>>> F
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
嵌套列表推导式
>>> [y + x for y in "abc" for x in "123"]
['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']