2维度列表如何在Python中运行(How do 2 dimentional lists work in Python)

编程入门 行业动态 更新时间:2024-10-22 18:30:41
2维度列表如何在Python中运行(How do 2 dimentional lists work in Python)

我正在做项目欧拉问题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 4523317656

Separate objects have separate memory id values, while your lists have the same result for each id() call, showing they are all the same list.

更多推荐

本文发布于:2023-07-14 20:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1107275.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:维度   如何在   列表   Python   lists

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!