python 组合问题出现的错误
我想要写一个函数能通过顶点和长宽高找到一个长方体八个顶点的坐标。
# x, y, z
v = ['x', 'y', 'z']
# length width height
th = ['L','W','H']
vertex = [None]*3
def ver(i):
if i <0 and vertex != []:
print vertex
else:
for x in ['+','-']:
t = v[i] + x + th[i] + ‘/2’
vertex[i] = t
ver(i-1)
['x+L/2', 'y+W/2', 'z+H/2']
['x-L/2', 'y+W/2', 'z+H/2']
['x+L/2', 'y-W/2', 'z+H/2']
['x-L/2', 'y-W/2', 'z+H/2']
['x+L/2', 'y+W/2', 'z-H/2']
['x-L/2', 'y+W/2', 'z-H/2']
['x+L/2', 'y-W/2', 'z-H/2']
['x-L/2', 'y-W/2', 'z-H/2']
就像是八皇后那样的方法,但是当我想把他们结果保存起来,而不是打印时,就不对了。
# x, y, z
v = ['x', 'y', 'z']
# length width height
th = ['L','W','H']
vertex = [None]*3
res = []
def ver(i):
if i <0 and vertex != []:
res.append(vertex)
else:
for x in ['+','-']:
t = v[i] + x + th[i]+'/2'
vertex[i] = t
ver(i-1)
ver(2)
print res
现在的res全都是['x-L/2', 'y-W/2', 'z-H/2']
[['x-L/2', 'y-W/2', 'z-H/2'], ['x-L/2', 'y-W/2', 'z-H/2'], ['x-L/2', 'y-W/2', 'z-H/2'], ['x-L/2', 'y-W/2', 'z-H/2'], ['x-L/2', 'y-W/2', 'z-H/2'], ['x-L/2', 'y-W/2', 'z-H/2'], ['x-L/2', 'y-W/2', 'z-H/2'], ['x-L/2', 'y-W/2', 'z-H/2']]
请问是为什么? python?递归?列表组合 python
[解决办法]
按结果res的每个元素都是同一对象,所以应该res.append(vertex[:])添加vertex副本当元素,这个副本就是另一个新对象,不会再跟着vertex变化...