在Python 有一种英语的语法,新手见到一脸懵逼,实际上它非常简单,便是一个英语的语法,不必太当一回事。了解它,会用就可以。
首先看一个事例
x, y = 1, 5 z = x if x > y else y # 假如x > y, z = x 不然 z = y print(z) # 5
关系式1 if 标准 else 关系式2 组成一个关系式。全部关系式的值,是那样计算的,假如if 后边的情况为真,全部三元运算符组成的关系式数值关系式1的值,假如为假,全部关系式的数值关系式2的值。
x, y = 1, 5 z = x if x > y else y # 假如x > y, z = x 不然 z = y print(z) # 5 z = x if x < y else y print(z) # 1
三元表达式的取代书写
x, y = 6, 8 z = (lambda : x , lambda : y) [x > y]() print(z) # 6 z = (lambda : x , lambda : y)[x < y]() print(z) # 8 x, y = 6, 8 z = (x, y)[x > y] print(z) # 6 z = (x, y)[x < y] print(z) # 8 x, y = 6, 8 z = {True: x, False: y}[x > y] print(z) # 8z = {True: x, False: y}[x < y] print(z) # 6 x, y = 6, 8 z = (x > y) and x or y print(z)z = (x < y) and x or y print(z)
三元表达式在Python中的运用十分普遍,我们可以看一下啊requests库文件的一段编码
# Default empty dicts for dict params. data = [] if data is None else data files = [] if files is None else files headers = {} if headers is None else headers params = {} if params is None else params hooks = {} if hooks is None else hooks self.hooks = default_hooks() for (k, v) in list(hooks.items()): self.register_hook(event=k, hook=v) self.method = method self.url = url self.headers = headers self.files = files self.data = data self.json = json self.params = params self.auth = auth self.cookies = cookies