将List作为参数传入后预期该list可变,结果未变

def merge( nums1, m, nums2, n):
    a=nums1[:m]
    b=nums2[:n]
    a.extend(b)
    print(a)
    nums1=a[:]
    print(nums1)
nums1=[1,2,3,0,0,0]
nums2=[2,5,6]
m=3
n=3
merge(nums1,3,nums2,3)
print(nums1)

预期以上程序执行后会输出:
[1, 2, 3, 2, 5, 6]
[1, 2, 3, 2, 5, 6]
[1, 2, 3, 2, 5, 6]
实际上输出的是:
[1, 2, 3, 2, 5, 6]
[1, 2, 3, 2, 5, 6]
[1, 2, 3, 0, 0, 0]
nums1未变,原因未知,因此询问诸位。

Jason990420
最佳答案

file

You can find the result as above as end of function merge. New lists created for a, b and nums1 assigned by slice of another list.

Do it like

nums1[m:] = nums2[:n]

then it will work !

file

4个月前 评论
HuberyZ 4个月前
讨论数量: 4
Jason990420

file

You can find the result as above as end of function merge. New lists created for a, b and nums1 assigned by slice of another list.

Do it like

nums1[m:] = nums2[:n]

then it will work !

file

4个月前 评论
HuberyZ 4个月前

Thanks for Jason990420's answer.

4个月前 评论
Jason990420

Python Tutor: Visualize code in Python, JavaScript, C, C++, and Java

Paste your code > Visualize Execution > Next (s)

4个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!