我有一个函数应该用“3D”数组表示一个立方体,但是一个图层中间有一个正方形。 I.E.
def cube(n):
list1 = []
list2 = []
list3 = []
for a in range(n+2):
list3.append(str('c'))
for b in range(n+2):
list2.append(list(list3))
for c in range(n+2):
list1.append(list(list2))
for d in range(1,n+1):
for e in range(1,n+1):
list1[0][d][e]='h'
return list1
pprint.pprint(cube(2))
>>>
[[['c', 'c', 'c', 'c'],
['c', 'h', 'h', 'c'],
['c', 'h', 'h', 'c'],
['c', 'c', 'c', 'c']],
[['c', 'c', 'c', 'c'],
['c', 'h', 'h', 'c'],
['c', 'h', 'h', 'c'],
['c', 'c', 'c', 'c']],
[['c', 'c', 'c', 'c'],
['c', 'h', 'h', 'c'],
['c', 'h', 'h', 'c'],
['c', 'c', 'c', 'c']],
[['c', 'c', 'c', 'c'],
['c', 'h', 'h', 'c'],
['c', 'h', 'h', 'c'],
['c', 'c', 'c', 'c']]]
但我想这样:
>>>
[[['c', 'c', 'c', 'c'],
['c', 'h', 'h', 'c'],
['c', 'h', 'h', 'c'],
['c', 'c', 'c', 'c']],
[['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c']],
[['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c']],
[['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c'],
['c', 'c', 'c', 'c']]]
仅限第一层中的h。为什么python会这样做?
答案 0 :(得分:2)
这是获得您想要的最小变化。首先,添加
from copy import deepcopy
然后替换:
list1.append(list(list2))
使用:
list1.append(deepcopy(list2))