python字符串vs列表奇数行为

2024-05-08 12:44:02 发布

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

如果我在二叉树上尝试下面的代码片段,然后尝试打印arr和字符串,arr会给出正确的结果,但是字符串是空的。有什么想法吗?这与通过引用传递的列表和通过值传递的字符串有关吗?你知道吗

def post_order(root, arr = []):
    if(root is not None):
        post_order(root.left, arr)
        post_order(root.right, arr)
        arr.append(root.value)

def post_order1(root, string = ''):
    if(root is not None):
        post_order1(root.left, string)
        post_order1(root.right, string)
        string += str(root.value)

# assume I've made my binary tree
arr, string = [], ''
post_order(root, arr)
post_order1(root, string)
print arr, string
# arr holds the correct post-order sequence
# string is empty

Tags: 字符串rightnonestringifisvaluedef
3条回答

Arr是一个数组,可以进行扩展。传递给post\ order1的字符串是一个不可变对象,更新时会创建一个副本。因此,原始字符串保持不变。你知道吗

您应该这样更正代码:

def post_order1(root, string = ''):
    if not root : return string

left  = post_order1(root.left, string)
right = post_order1(root.right, left)
return right + str(root.value)

在Python中,列表是可变的,字符串是不变的。这意味着可以修改列表,但不能修改字符串。只能重新分配字符串。你知道吗

在函数中,您使用.append()修改列表,但只重新分配字符串+=

相关问题 更多 >