如何在列表类型中“扩展”静态

时间:2017-11-21 17:04:30

标签: python

我是python 3的初学者。 我做了三次内部列表,如

[[[1, 0, 3], [1, 11, 1]], [[1, 0, 3], [1, 11, 1]]].

我的问题是如何静态扩展列表。

这是我的代码

import numpy as np
TestList0=[]
TestList_log=[]
for m in range(2):
    TestList = np.random.randint(0,4,3)
    TestList0.append([])
    TestList0[m].extend(TestList)

for time in range(3):
    TestList0[1][1] = TestList0[1][1]+5
    TestList_log.append([])
    TestList_log[time].extend(TestList0)    
    print(TestList_log)

,输出

[[[2, 0, 1], [1, 7, 0]]]
[[[2, 0, 1], [1, 12, 0]], [[2, 0, 1], [1, 12, 0]]]
[[[2, 0, 1], [1, 17, 0]], [[2, 0, 1], [1, 17, 0]], [[2, 0, 1], [1, 17, 0]]]

似乎动态插入“TestList0”。 我想要获得的是

[[[2, 0, 1], [1, 7, 0]]]
[[[2, 0, 1], [1, 7, 0]], [[2, 0, 1], [1, 12, 0]]]
[[[2, 0, 1], [1, 7, 0]], [[2, 0, 1], [1, 12, 0]], [[2, 0, 1], [1, 17, 0]]]

我该怎么办?看起来双重内部列表是静态的

for time in range(3):
    TestList0[1][1] = TestList0[1][1]+5
    TestList_log.append([])
    TestList_log[time].extend(TestList0[1])    
    print(TestList_log)

输出

[[1, 7, 3]]
[[1, 7, 3], [1, 12, 3]]
[[1, 7, 3], [1, 12, 3], [1, 17, 3]]

对我来说,在三重和双重内部列表之间出现这种差异看起来很奇怪。 我将不胜感激任何帮助和解释。谢谢!

1 个答案:

答案 0 :(得分:1)

我碰巧自己找到了解决方案。 让我分享一下。 这是可变的或不可改变的,不是静态的或动态的。

我应该做的是改变

TestList_log[time].extend(TestList0)  

import copy
TestList_log[time].extend(copy.deepcopy(TestList0))
相关问题