【问题标题】:Python While Loop SyntaxPython While 循环语法
【发布时间】:2016-07-06 17:32:38
【问题描述】:
class Solution: 
    def display(self,head):
        current = head
        while current:
            print(current.data,end=' ')
            current = current.next

你好,我在理解上面的while循环时遇到了一些困难,AFAIK你需要有一个while循环的条件,所以:

while (stuff) == True:

但是上面的代码有:

while current:

这是否与:

while current == head:

谢谢

【问题讨论】:

  • 您似乎对while循环上方语句的含义感到困惑。它与循环无关或它是有条件的。相反,它将变量head 复制到变量current。然后将电流转换为布尔值并检查它的“真实性”,如下面的Mariusz Jamroanswer 解释的那样。

标签: python loops while-loop


【解决方案1】:

while current: 语法的字面意思是while bool(current) == True:。该值将首先转换为布尔值,然后与True 进行比较。在 python 中,每一个转换为 bool 的都是 True,除非它是 NoneFalse、零或空集合。

请参阅truth value testing 部分以供参考。

【讨论】:

  • 谢谢,现在有意义了
【解决方案2】:

你的循环可以被认为是

while current is not None:

因为解析器会尝试将 current 解释为布尔值(并且 None、空列表/元组/字典/字符串和 0 评估为 False)

【讨论】:

  • 不,更像while current is not None and current is not False and current is not [] and current is not {} and current is not 0 and current is not "":。其实是while bool(current) == True:
  • 除了None,Python 中还有其他虚假值,所以这是不正确的。
  • 我已将答案编辑为更完整...但如果没有下一个元素, current.next 最有可能返回 None 。而且while bool(current)就够了,不用检查是否与True相等
【解决方案3】:

变量current的值就是条件。如果为真,则循环继续,如果为假,则循环停止。期望在链表的最后一个元素中,next 将包含一个假值。我假设该值为None,在这种情况下,循环等效于:

while Current is not None:

如果链表使用false作为结束标记,则相当于:

while Current != false:

【讨论】:

  • Python 中除了 None 之外还有其他虚假值,所以这是不正确的。
  • 我说“我假设该值为 None”,因为这是实现此类事情的典型方式。
猜你喜欢
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
相关资源
最近更新 更多