简体   繁体   English

"无法从函数中就地修改 Python 列表"

[英]Unable to modify Python List in-place from within Function

We have a function rotate()<\/code> that takes a list nums<\/code> and modifies it in-place.我们有一个函数rotate()<\/code> ,它接受一个列表nums<\/code>并就地修改它。 However I am unable to get the correctly modified list from after the rotate()<\/code> function call.但是,在rotate()<\/code>函数调用之后,我无法获得正确修改的列表。

Why is this happening?为什么会这样?

def rotate(nums, k):
    """
    Rotate the list to the right by k steps
    Do not return anything, modify nums in-place instead.
    """

    # Reverse
    nums.reverse()
    a = nums[:k]
    a.reverse()
    b = nums[-(len(nums)-k):]
    b.reverse()
    nums = a + b
    print('Inside function:', nums)

nums = [1,2,3,4,5,6]
rotate(nums, 3)
print('Outside function: ', nums)      

The line:该行:

nums = a + b

You have to use inplace-methods on your list, eg del<\/code> and extend<\/code> :您必须在列表中使用 inplace-methods,例如del<\/code>和extend<\/code> :

def rotate(nums, k):
    a = nums[:-k]
    del nums[:-k]
    nums.extend(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM