两种语法:
举例说明:
1、[expression for iter_val in iterable]
传统写法:
L = []
for i in range(1,11):
L.append(i**2)
print(L)
输出:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
列表解析:
L = [i**2 for i in range(1,11)]
print(L)
输出:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
2、[expression for iter_val in iterable if cond_expr]
传统写法:
L = []
for i in range(1,11):
if i**2 > 50:
L.append(i**2)
print(L)
输出:
[64, 81, 100]
列表解析:
L = [i**2 for i in range(1,11) if i**2 >50]
print(L)
输出:
[64, 81, 100]