常用三元运算符来简化分支和循环的代码:
分支简化:
a = 1b = 2c = a if a > 1 else bprint(c)
# 以上几行等同于
a = 1b = 2if a >1: c = aelse: c = bprint(c)
循环简化:
nums = list(range(1,11))s = [i for i in nums if i % 2 == 0]print(s) # 以上代码等同于
s = []nums = list(range(1,11))for i in nums: if i % 2 == 0: s.append(i)print(s)
时间: 2024-12-14 22:29:26