在python中复制列表 [英] copy list in python

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

问题描述

我正在尝试制作列表的副本,并使用列表的副本做一些事情.不知何故,我的原始列表也被修改了.我已经研究过不同的内存分配方式和分配列表的不同方式.到目前为止没有运气...有什么想法吗?

As I am trying to make a copy of a list and do some stuff with the copy of the list. Somehow my original list is modified as well. I already looked at different memory allocatinos and different ways of assigning the lists. So far no luck... Any ideas?

    row = 0
    column = 0
    table1 = copy.copy(table[:])

    temptable = []
    temptable = table[:]

    print id(table)
    print table
    print id(table1)
    print table1
    print id(temptable)
    print temptable

    for i in temptable:
        for j in i:
            if type(j) == str:
                temptable[row][column] = 0
            column = column + 1
        column = 0
        row = row + 1
    result=[]   

    for column in zip(*temptable):
        try:
                result.append(sum(map(int,column)))
            except ValueError:
                result.append(0)


    print table
    print table1
    print temptable

/####结果

163783148
[[0, 'ZZZ', 'XXX', 'YYY', 'AAA', 0, 0], ['BBB', 1, 1, 0, 26, 28, 0], ['CCC', 26, 0, 0, 0, 26, 0], ['DDD', 0, 26, 0, 0, 26, 0], ['EEE', 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]

163669036
[[0, 'ZZZ', 'XXX', 'YYY', 'AAA', 0, 0], ['BBB', 1, 1, 0, 26, 28, 0], ['CCC', 26, 0, 0, 0, 26, 0], ['DDD', 0, 26, 0, 0, 26, 0], ['EEE', 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]

163783468
[[0, 'ZZZ', 'XXX', 'YYY', 'AAA', 0, 0], ['BBB', 1, 1, 0, 26, 28, 0], ['CCC', 26, 0, 0, 0, 26, 0], ['DDD', 0, 26, 0, 0, 26, 0], ['EEE', 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]

[[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 26, 28, 0], [0, 26, 0, 0, 0, 26, 0], [0, 0, 26, 0, 0, 26, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]

[[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 26, 28, 0], [0, 26, 0, 0, 0, 26, 0], [0, 0, 26, 0, 0, 26, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]

[[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 26, 28, 0], [0, 26, 0, 0, 0, 26, 0], [0, 0, 26, 0, 0, 26, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]

推荐答案

您的原始列表包含内部列表:

Your original list contains inner lists:

[[0, 'ZZZ', 'XXX', 'YYY', 'AAA', 0, 0], 
 ['BBB', 1, 1, 0, 26, 28, 0], ...
]

内部列表实际上存储为引用,即:

The inner list are actually stored as references, i.e.:

[ location-of-list-0, 
  location-of-list-1, ...
]

复制列表时,实际上是将引用列表复制到原始列表中存储的相同列表中.这称为浅表复制,因为它复制引用而不是内容.

When you copied the list, you actually copied a list of references to the same lists stored in your original list. This is called shallow copy, as it copies references rather than contents.

使用深度复制创建一个完全独立的列表.

Use deep copy to create a totally separate list.

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

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