我正在做项目欧拉问题15 。 我使用了正确的算法,但它似乎没有用。 这是我的代码:
f = [[0] * 21] * 21 # init the list for i in range(21): f[0][i] = 1 f[i][0] = 1 for i in range(21): for j in range(21): f[i][j] = f[i-1][j] + f[i][j-1] print f[20][20]当我完成列表的初始化时,我将其打印出来。 我期望它像[[1, 1, 1...], [1, 0, 0...]...] ,但它变成[[1, 1, 1...], [1, 1, 1...]...]我无法理解为什么。
我曾经使用类C语言,我认为Python中的列表有点像C中的数组,所以我以相同的方式使用它们。
I am doing Project Euler Problem 15. I used the right algorithm, but it didn't seem to work. Here's my code:
f = [[0] * 21] * 21 # init the list for i in range(21): f[0][i] = 1 f[i][0] = 1 for i in range(21): for j in range(21): f[i][j] = f[i-1][j] + f[i][j-1] print f[20][20]when I finished initializing the list, I printed it. I expected it like [[1, 1, 1...], [1, 0, 0...]...], but it turned [[1, 1, 1...], [1, 1, 1...]...] and I can't figure why.
I used to use C-like language and I thought the list in Python is kind of like the array in C, so I used them in the same way.
最满意答案
乘以列表时,您不是创建单独的列表,而是创建对同一列表的多个引用 。
相反,这样做:
f = [[0 for _ in range(21)] for _ in range(21)]使用id()函数时可以看到区别:
>>> f = [[0]*21]*21 >>> for nested in f[:3]: ... print id(nested) ... 4523317152 4523317152 4523317152 >>> f = [[0 for _ in range(21)] for _ in range(21)] >>> for nested in f[:3]: ... print id(nested) ... 4523317512 4523317440 4523317656单独的对象具有单独的内存ID值,而您的列表对每个id()调用具有相同的结果,显示它们都是相同的列表 。
When multiplying a list, you are not creating separate lists but rather create multiple references to the same list.
Instead, do this:
f = [[0 for _ in range(21)] for _ in range(21)]You can see the difference when using the id() function:
>>> f = [[0]*21]*21 >>> for nested in f[:3]: ... print id(nested) ... 4523317152 4523317152 4523317152 >>> f = [[0 for _ in range(21)] for _ in range(21)] >>> for nested in f[:3]: ... print id(nested) ... 4523317512 4523317440 4523317656Separate objects have separate memory id values, while your lists have the same result for each id() call, showing they are all the same list.
更多推荐
发布评论