如果切片不创建列表的副本,也不是list()如何获得我的列表的真实副本? [英] If slicing does not create a copy of a list nor does list() how can I get a real copy of my list?

查看:422
本文介绍了如果切片不创建列表的副本,也不是list()如何获得我的列表的真实副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修改一个列表,由于我的修改有点棘手,我的列表很大,我使用下面的代码

I am trying to modify a list and since my modifications were getting a bit tricky and my list large I took a slice of my list using the following code

tempList=origList[0:10]
for item in tempList:
    item[-1].insert(0 , item[1])
    del item[1]

我这样认为对列表的所有修改都会影响tempList对象origList对象。

I did this thinking that all of the modifications to the list would affect tempList object and not origList objects.

一旦我获得了我的代码,并在我的原始列表上运行它的前十个项目(索引为0-9)受我的操作影响测试代码打印上面。

Well once I got my code right and ran it on my original list the first ten items (indexed 0-9) were affected by my manipulation in testing the code printed above.

所以我google了一下,我发现有一些参考资料表示,片子复制列表并创建一个新的。我还发现了代码,帮助我找到项目的ID,所以我从头开始创建我的origList,获得前十个项目的ID。我再次切片列表,发现来自切片的ids匹配来自origList的前十个项目的ids。

So I googled it and I find references that say taking a slice copies the list and creates a new-one. I also found code that helped me find the id of the items so I created my origList from scratch, got the ids of the first ten items. I sliced the list again and found that the ids from the slices matched the ids from the first ten items of the origList.

我发现更多的笔记,建议一个更pythonic的方式复制列表将使用

I found more notes that suggested a more pythonic way to copy a list would be to use

tempList=list(origList([0:10])

我试过,我仍然发现,从tempList的id匹配来自origList的id。

I tried that and I still find that the ids from the tempList match the ids from the origList.

请不要提出更好的方法来编写代码 - 我想知道如何在列表中做这件事。理解复制的工作原理后,我自己理解

Please don't suggest better ways to do the coding-I am going to figure out how to do this in a list Comprehension on my own after I understand what how copying works

基于Kai的回答,正确的方法是:

Based on Kai's answer the correct method is:

import copy
tempList=copy.deepcopy(origList[0:10])
id(origList[0])
>>>>42980096
id(tempList[0])
>>>>42714136

如同魅力一样工作

推荐答案

切片创建一个浅拷贝在你的例子中,我看到你在item [-1]上调用insert(),这意味着item是一个列表的列表。这意味着你的浅拷贝仍然引用原始对象。您可以将其视为指针的副本,而不是实际的对象。

Slicing creates a shallow copy. In your example, I see that you are calling insert() on item[-1], which means that item is a list of lists. That means that your shallow copies still reference the original objects. You can think of it as making copies of the pointers, not the actual objects.

您的解决方案在于使用深度副本。 Python提供了一个复制模块只是这种事情。您可以在搜索时找到有关浅层和深层复制的更多信息。

Your solution lies in using deep copies instead. Python provides a copy module for just this sort of thing. You'll find lots more information on shallow vs deep copying when you search for it.

这篇关于如果切片不创建列表的副本,也不是list()如何获得我的列表的真实副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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