【问题标题】:Different between while i and j / while j and i in python [duplicate]python中的while i和j / while j和i之间的区别[重复]
【发布时间】:2023-03-03 02:14:01
【问题描述】:

我正在尝试做 leetcode #83 我不明白的是以下两种方式有什么区别:

    while cur and cur.next:

    while cur.next and cur:

如果我尝试第二种方式,它会出现编译错误。 谁能帮我理解这个概念?

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None

    class Solution(object):
        def deleteDuplicates(self, head):
            """
            :type head: ListNode
    :rtype: ListNode
    """
    cur= head
    while cur and cur.next:
        if cur.val== cur.next.val:
            cur.next= cur.next.next
        else: 
            cur = cur.next

    return(head)

我是数据结构的初学者。 我仍然困惑为什么 cur.next 是错误方式。代码 cur = head 不起作用?

【问题讨论】:

  • 给您和读者的小提示:None 的比较应该是definitely be done with iswhile cur is not None and cur.next is not None
  • 不同意。 while cur and cur.next 是惯用的。与None 比较时,PEP8 只说使用is 而不是==。它并不坚持使用value is not None 而不是简单的value

标签: python data-structures


【解决方案1】:

它叫做short circuit evaluation。如果 cur 为 None,解释器甚至不会尝试检查 cur.next。

【讨论】:

  • 我仍然很困惑为什么 cur.next 是错误方式。代码 cur = head 不起作用?为什么 cur 是 None?
  • @Esther 你遍历一个链表,当你到达末尾时,由于cur = cur.next,cur 将变为 None。
猜你喜欢
  • 2013-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 2013-08-19
  • 1970-01-01
  • 2012-10-20
  • 1970-01-01
相关资源
最近更新 更多