列表推导式有两种形式,如下:
1⃣️ [e for e in lists if condition]
结果·是一个数据列表
2⃣️ [exp1 if condition else exp2 for e in lists if other condition]
if else起赋值作用,满足条件exp1,不满足条件exp2,结果返回一个数据列表
一个复杂的例子:
[e if e != '/n' else '换行' for e in ['您好', '/n', '我是36467号,', '请问你要', '打猎', '吗?', 'null'] if e != 'null']
一个简单的例子:
# 1-100里的整十数
[e for e in range(1,101) if e % 10 == 0]
# 1-100里的整十数保持不变,其它数变为-1
[e if e % 10 == 0 else -1 for e in range(1,101)]