您能解释一下我用这行代码在python中得到什么吗?该代码创建什么?
NP = 2
NB = 2
ND = 2
N = NP*NB*ND
M = 2*N + NP*NB
res = [[None] * 3] * (M)
谢谢!
答案 0 :(得分:0)
如果您实际运行代码,您将得到
>>> res
[[None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None]]
但是,值得一提的是,顶层列表中的列表实际上是一个重复多次的单个列表,因此,对一个变量进行变异会使其全部变异:
>>> res[0][1] = 'x'
>>> res
[[None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None], [None, 'x', None]]