python - 如果写作的行为方式不同,为什么经典和内联?
问题描述
我得到了这个代码
firstId = True
for x in [1,2,3,4,5]:
firstId = False if firstId else print(str(x)+ " " + str(firstId))
print ("What is happening here ???")
firstId = True
for x in [1,2,3,4,5]:
if firstId:
firstId = False
else:
print(str(x)+ " " + str(firstId))
奇怪的是我有这个输出
2 False
3 None
4 None
5 None
What is happening here ???
2 False
3 False
4 False
5 False
据我了解,两个 if 语句的行为方式应该相同。但布尔值不是。我不明白为什么布尔值以某种方式变为无。有人可以解释发生了什么吗?
解决方案
这个:
firstId = False if firstId else print(str(x)+ " " + str(firstId))
是相同的
firstId = (False if firstId else print(str(x)+ " " + str(firstId)))
IE
if firstId:
firstId = False
else:
firstId = print(str(x)+ " " + str(firstId))
它总是给 赋一个值firstId
,右边的条件表达式决定了那个值是什么。
在这种else
情况下,该值为 None,因为print(...)
返回 None。
条件表达式不是单行 if 语句。它是用于不同目的的不同结构。
推荐阅读
- php - 如何修复显示 page/1/ 的分页
- java - 如何使用 JAVA 中的嵌套 for 循环打印以下模式?
- java - 覆盖没有别名的spring bean,它也是父级
- python - 在烧瓶中导入 YAML
- angular - 错误 TS2339:类型“{生产:布尔值”上不存在属性“对话流”;}'
- c++ - 为 c++ 源文件构建 debian 包时出错
- android - RecyclerView 在滚动时丢失了它的项目位置
- javascript - 如何在javascript中分割文本
- unity3d - 需要帮助实施 Perforce depot 或 GitHub repot,允许异地云托管与本地计算机之间的现场主服务器同步
- pandas - 在 pandas 的 groupby 期间根据列是否包含特定字符串来创建变量