赞
踩
第一种
value = "变量1" if a>b else "变量2"
第二种
value = ("变量1","变量2")[a>b]
第三种
value = {"变量1","变量2"}[a>b]
传统写法
if a>b :
value = "变量1"
else :
value = "变量2"
单层for循环
# 传统写法
v = []
for r in [1,2,3]:
v.append(r+1)
# 简写
v = [r+1 for r in s]
# v 输出 [2, 3, 4]
双层for循环
rrr = [[1,2],[3,4]]
# 传统写法
v = []
for rr in rrr:
for r in rr:
v.append(r+1)
# 简写
v = [r+1 for rr in rrr for r in rr]
# v 输出 [2, 3, 4, 5]
for循环+if
x = [1,2,3,4,5,6,7]
# 传统写法
for i in x:
if i>3:
print(i)
# 简写
[print(i) for i in x if i>3 ]
例:
x = 3
v = (lambda k: k+3)(x)
# v 输出6
例:
v = list(map(lambda x: x * 2, [1, 2, 3, 4, 5]))
# v 输出: [2, 4, 6, 8, 10]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。