Python更改相等对象?

2024-04-26 22:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

    def __repr__(self):
        if self:
            return "{} -> {}".format(self.val, self.next)


class Solution(object):
    def mergeTwoLists(self, l1, l2):
        curr = dummy = ListNode(0)
        while l1 and l2:
            if l1.val < l2.val:
                curr.next = l1
                l1 = l1.next
            else:
                curr.next = l2
                l2 = l2.next
            curr = curr.next
        curr.next = l1 or l2
        return dummy.next

ln1 = ListNode(1)
ln2 = ListNode(2)
ln3 = ListNode(4)
ln4 = ListNode(1)
ln5 = ListNode(3)
ln6 = ListNode(4)
ln1.next = ln2
ln2.next = ln3
ln4.next = ln5
ln5.next = ln6

s = Solution()
result = s.mergeTwoLists(ln1, ln4)
print(result)

解决leetcode问题的python代码#21。问题是当代码在curr.next = l1curr.next = l2运行时,curr会发生变化,dummy也会发生变化。但是,当在curr = curr.next运行时,只有curr运行,但dummy不会改变。为什么会这样

Python中的类似情况如下:

a = b = [1, 2, 3]
b = [1, 2, 3, 4]
print(a)

a = b = [1, 2, 3]
b.append(4)
print(a)

第一个a没有改变,但是第二个a改变了


Tags: selfl1defvalclassdummynextprint