在python中获取没有if或for块的列表元素

几天前,在我的考试中,我遇到了这个问题: 4. 不用 if 语句重写以下代码。代码应该是单行的。(不使用任何其他循环)

If not flora and fauna:
      return True
else:
      return False

我无法回答这个问题,但对我来说仍然很有趣/奇怪,因为我不是 Python 专家。我已经尝试了很多方法,比如extend()函数,但仍然不知道如何做到这一点。

任何想法或提示?

编辑:我错误地提出了这个问题。非常遗憾。由于我没有太多经验,我认为这个问题只能通过列出来解决。

回答

由于您True在 theif为真False时返回,当它为假时返回,直接的解决方案是直接返回if正在评估的内容:

return not flora and fauna

请注意,这可能不会返回Trueor False,而是一个真值或假值(例如,对于假值flora,表达式的计算结果fauna为 ;如果flora, fauna = 0, "Spam",表达式的计算结果为"Spam",即为真值,但不是True),并且fauna"Spam"。如果您需要一个真正的True/ False,只需转换为bool

return bool(not flora and fauna)

或者使用条件表达式来达到同样的效果:

return True if not flora and fauna else False

或者(我们现在正在进入“玩乐领域):

return not not (not flora and fauna)

或(分发一份not):

return not (flora or not fauna)

或(比 快,比boolnot not,但可能不值得导入):

from operator import truth

return truth(not flora and fauna)

不过,在 99+% 的情况下,您不需要 true True/ False,因此return not flora and fauna确实是要走的路。


以上是在python中获取没有if或for块的列表元素的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>