方法内的切片列表(Python 3) [英] Slicing list inside a method (Python 3)

查看:99
本文介绍了方法内的切片列表(Python 3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下方法:

def slice_list(my_list, slice_point):
    my_list = my_list[:slice_point]
    print("Inside method: ", my_list)

    return 

我对此进行了如下测试:

I have a test for it like the following:

if __name__ == "__main__":
    my_list = [1,2,3,4,5]
    slice_point = 3

    slice_list(my_list, slice_point)
    print("Outside method: ", my_list)

在列表没有最终编辑的意义上,我得到的输出不是我期望的.

The output I get is not what I expected for, in the sense that the list is not ultimately edited

>>>Inside method:  [1, 2, 3]
>>>Outside method:  [1, 2, 3, 4, 5]

但是当我对列表执行append时,它确实编辑了列表,如以下示例所示:

But when I do an append to the list, it does edit the list for good, as this example shows:

def append_to_list(my_list, element):
    my_list.append(element)
    print("Inside method: ", my_list)

    return 

if __name__ == "__main__":
    my_list = [1,2,3,4,5]
    append_to_list(my_list, "new element")
    print("Outside method: ", my_list)

哪个给出以下输出:

>>>Inside method:  [1, 2, 3, 4, 5, 'new element']
>>>Outside method:  [1, 2, 3, 4, 5, 'new element']

为什么切片无法永久更改列表?

推荐答案

尝试以下方法:

my_list[:] = my_list[:slice_point]

您的旧方法只是将名称my_list指向一个新对象,即该切片返回的副本.

Your old method just points the name my_list at a new object, i.e. at the copy returned by the slice.

但是,我上面提出的建议修改了my_list最初指向的对象,而没有重新绑定该名称.

The suggestion I've proposed above, however, modifies the object which my_list originally pointed at without rebinding that name.

这篇关于方法内的切片列表(Python 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆