python - if not 声明解释
问题描述
此代码是在我找到的答案中提供的,但没有解释。我想知道为什么需要包含“非消息”才能使其正常工作?
def first_and_last(message):
if not message or message[0] == message[-1]:
return True
else:
return False
解决方案
If message
happens to be an empty list []
then you will throw an IndexError
because message[0]
and message[-1]
do not exist in the list
.
Generally, if not
checks to see if something is Truthy or Falsey. (A great example of what is falsey is here)
In this example, if you pass []
which happens to be falsey, it will trigger the boolean comparison and since comparisons like or
are lazy loaded, it will not even check message[0] == message[-1]
which would throw an error.
If you know that message
always be a list
and will never be Falsey (i.e. None
, []
, ''
, etc.) then you do not need it.
推荐阅读
- excel - 如何在活动单元格中打开用户窗体?
- python - 当列的总和为 0 时,将单元格标记为 1
- android - 哪些方法使用 androidManifest 文件中定义的权限?
- typescript - 排除使用的方法
- java - 就像后增量一样,我们在 java 中是否有后分配?
- azure - 从门户恢复已删除的 Azure SQL 数据库 - 部署失败并出现 InternalServerError
- java - 如何在 GridBagLayout 中嵌套 JPanel?
- abap - ABAP 程序在用户帐户被禁用前 X 天通知用户
- javascript - 我在 react 中的过滤器搜索列表不显示过滤后的列表并遇到错误
- python - python numpy 列表操作