python - python表达式的评估
问题描述
我在 python 中遇到了以下表达式来评估一个数字是奇数还是偶数。虽然它看起来很优雅,但我很惊讶地看到它起作用了。我猜对于输入3
:
x%2
等于1
计算结果为True
,非空字符串(odd
)计算结果为True
。所以我们有True and True or <don't have to check because it doesn't matter if True or False as the overall statement will be True>
. 但是为什么在那种情况下的输出不是True
-odd
我错过了什么概念?
>>> (lambda x:
... (x % 2 and 'odd' or 'even'))(3)
'odd'
解决方案
and
andor
运算符不限于 True 和 False ;他们返回他们的操作数之一。
>>> 1 and "odd"
'odd'
>>> 0 or "even"
'even'
推荐阅读
- android - 删除多个表 execSQL
- html - HTML表格填充不起作用
- json - JSON Postman 正文不适用于 PostgreSQL 插入
- javascript - Jquery Datatable - 从服务器中提取数据 - 如何将值用作属性
- sql-server - 如果 SELECT 中的一个或多个链接服务器脱机,则链接服务器 SELECT UNION 结果
- ios - 尝试将过滤器与 Swift 4、IOS 11 一起使用时出现错误消息
- javascript - 这两行代码有什么区别?
- javascript - 反应不渲染类
- javascript - 如果未单击页面,为什么 onbeforeunload 不会触发?
- c# - 通过位移组合两个可变长度的字节数组