赞
踩
点击上方“Python3X”,选择“置顶或者星标”
第一时间收到精彩推送!
Python Every Day, 第 22 天
x, y = 1, 5z = x if x > y else y # 如果x > y, z = x 否则 z = yprint(z) # 55z = x if x > y else y # 如果x > y, z = x 否则 z = yprint(z) # 5
'运行
表达式1 if 条件 else 表达式2 构成一个表达式。 整个表达式的值,是这样计算的,如果if 后面的条件为真,整个三元操作符构成的表达式值为表达式1的值,如果为假,整个表达式的值为表达式2的值。
x, y = 1, 5z = x if x > y else y # 如果x > y, z = x 否则 z = yprint(z) # 5z = x if x < y else yprint(z) # 15z = x if x > y else y # 如果x > y, z = x 否则 z = yprint(z) # 5z = x if x < y else yprint(z) # 1
x, y = 6, 8z = (lambda : x , lambda : y) [x > y]()print(z) # 6z = (lambda : x , lambda : y)[x < y]()print(z) # 88z = (lambda : x , lambda : y) [x > y]()print(z) # 6z = (lambda : x , lambda : y)[x < y]()print(z) # 8
'运行
x, y = 6, 8z = (x, y)[x > y]print(z) # 6 z = (x, y)[x < y]print(z) # 88z = (x, y)[x > y]print(z) # 6 z = (x, y)[x < y]print(z) # 8
x, y = 6, 8z = {True: x, False: y}[x > y]print(z) # 8z = {True: x, False: y}[x < y]print(z) # 68z = {True: x, False: y}[x > y]print(z) # 8z = {True: x, False: y}[x < y]print(z) # 6
'运行
x, y = 6, 8z = (x > y) and x or yprint(z)z = (x < y) and x or yprint(z)8z = (x > y) and x or yprint(z)z = (x < y) and x or yprint(z)
三元表达式在Python中的应用非常广泛,我们可以看一下啊requests库中的一段代码
# Default empty dicts for dict params.data = [] if data is None else datafiles = [] if files is None else filesheaders = {} if headers is None else headersparams = {} if params is None else paramshooks = {} if hooks is None else hooksself.hooks = default_hooks()for (k, v) in list(hooks.items()): self.register_hook(event=k, hook=v)self.method = methodself.url = urlself.headers = headersself.files = filesself.data = dataself.json = jsonself.params = paramsself.auth = authself.cookies = cookiesdata = [] if data is None else datafiles = [] if files is None else filesheaders = {} if headers is None else headersparams = {} if params is None else paramshooks = {} if hooks is None else hooksself.hooks = default_hooks()for (k, v) in list(hooks.items()): self.register_hook(event=k, hook=v)self.method = methodself.url = urlself.headers = headersself.files = filesself.data = dataself.json = jsonself.params = paramsself.auth = authself.cookies = cookies
'运行
感谢您的阅读
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。