python - eval函数Python的错误输出
问题描述
你能解释一下为什么这个表达式的计算结果为 0 吗?
eval("(2==2|2==3)") # this is evaluated to 0 instead of 1
谢谢
解决方案
您使用了错误的运算符,因此您也得到了错误的优先级。
在 Python 中,or
的优先级低于==
, 而|
具有更高的优先级。您的表达式被评估为2 == (2|2) == 3
which is 2 == 2 == 3
which is False
。
你想要2 == 2 or 2 == 3
which 被评估为(2 == 2) or (2 == 3)
which is True
。
推荐阅读
- php - Laravel 显示来自 foreach 的对象
- python - 使用 NamedAgg 聚合带有条件的 Pandas DataFrame
- c# - LINQ to Objects - 减少重复 - 在 select 语句中映射
- aws-sam - AWS SAM - 配置 TOML 文件
- c# - 如何找到发送http请求的时间C#
- php - 如果 PHP 中的值为空,如何取消设置数组
- r - 计算R中多个坐标的距离
- javascript - 按钮 onClick 不能与此 JS 一起使用或以编程方式触发 jquery Resizable Font-size?
- c# - CSVHelper 指数用逗号代替点
- javascript - Electron vue 应用程序 - 使用私有 repo 更新应用程序