python3的列表生成式主要有3种:
- for循环+if ------- [i for i in xxx if x xxx]
- for循环+if else --------- [i if exp1 else exp2 for i in xxx]
- 多层for循环 ----------- [for i in xxx for j in xxx]
# 列表生成式1 for循环+if
# [i for i in xxx if x xxx]
# 此处的if语句主要起判断的作用,if在后
a = [i for i in [1,2,3,4] if i > 2]
print(a)
# 列表生成式2 for循环+if else
# [i if exp1 else exp2 for i in xxx]
# 此处的if else语句主要起赋值的作用,if---else----在前
a = [i if i>2 else 0 for i in [1,2,3,4,5]]
print(a)
# 列表生成式3 多层for循环
# [for i in xxx for j in xxx]
a = [i+j for i in 'abc' for j in 'mnp']
print(a)
结果: