切片列表而不复制 [英] Slicing a list without copying

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

问题描述

这是我在论坛上的第一个问题,我也是Python的新手,所以也许这没有什么意义,但我只是想知道...

This is my first question on the forum and I'm also really new to Python, so maybe this doesn't make a lot of sense, but I'm just left wondering...

这非常相关,但是IMO这个问题切片列表在Python中没有生成副本不能回答如何以更改切片会更改原始切片的方式切片列表的问题?

It's very related, but IMO this question Slicing a list in Python without generating a copy does not answer the question of how to slice a list in such a fashion that changing the slice would change the original?

说,如果我只想更改函数中列表的一部分,并确保该函数无权访问所有成员,那我该怎么写:

Say, if I want to change only part of a list in a function and make sure that the function doesn't have access to all the members, how do I write this:

def myFunc(aList):
    for i in range(0,len(aList)):
        aList[i] = 0

wholeList = range(0,10)
partOfList = wholeList[3:6]
myFunc(partOfList)

,这样最后的 wholeList 将是

[0, 1, 2, 0, 0, 0, 6, 7, 8, 9] 

??

我想如果 wholeList 的内容是可变对象,这是可行的,但是带数字是让 myFunc 返回更改后的列表并在调用工作区?

I guess this would work if the contents of wholeList were mutable objects, but with numbers is the only way to have the myFunc return the changed list and assign in the calling workspace?

推荐答案

如果只想修改列表的一部分,则只能发送该切片,并使用 return将修改分配给同一部分:

If you want to modify just a part of the list, you can send in only that slice, and assign the modifications to that same section using return:

def myFunc(aList):
    for i in range(0,len(aList)):
        aList[i] = 0
    return aList

wholeList = range(0,10)
wholeList[3:6] = myFunc(wholeList[3:6])

否则,正如您之前所说的,您只是在创建新列表以碰巧引用原始切片中包含的内容,您必须将对新列表的所有修改重新分配回旧列表.

Otherwise as you said before, you are just creating new lists that happen to reference what is contained in the slice of the original, you'll have to reassign any modifications to the new list back into the old one.

为进一步说明, wholeList [3:6] partOfList 元素是相同的对象.但是列表只是对那些对象的引用.所以 id(wholeList [3])== id(partOfList [0]),但是如果我们更改其中一个引用,例如 partOfList [0] = 10 ,则我们将 partOfList [0] 引用更改为 10 ,而不是实际的对象( 3 ).因此,在此修改中,没有任何操作会反映 wholeList 中的任何更改,因为它仍在引用原始对象.

To further clarify, the elements of wholeList[3:6] and partOfList are the same objects. But the lists are just references to those objects. So id(wholeList[3]) == id(partOfList[0]), but if we change one of those references, eg partOfList[0] = 10, then we change the reference of partOfList[0] to 10 not the actual object (3) that was being pointed to. Thus there is no action in this modification that would reflect any changes in wholeList, since it is still referencing the original object..

这篇关于切片列表而不复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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