繁多的操作者*
在座标上的工作有一些缺点。
More generally, there are differences on its effects when applied on immutable objects such integers or strings, and how those it has when applied on mutable objects like lists and dictionaries.
这可能澄清问题:
>>> l = [0] * 3 #a list of immutable integers
>>> l
[0, 0, 0]
>>> l[0] = 1
>>> l
[1, 0, 0]
>>> l = [[0]] * 3 #a list of mutable lists
>>> l
[[0], [0], [0]]
>>> l[0][0] = 1
>>> l
[[1], [1], [1]]
<EDIT (评论中的库多斯到@lazyr) 在上述两种情况下,<代码>*的操作者都编制了具有相同特性的物体清单(主题地址),因此,各阵列中的每个编号(和每个清单)实际上都是相同的物体,但不可更改的类型只能替换,因此,如果你试图将新数值分配给各立体,则你将实际替换整个物体,而清单中的情况并非如此。 沿用前例(铭记id
功能返回物体的记忆地址:
>>> m = [1] * 3
>>> id(m[0])
39356344
>>> id(m[1])
39356344
>>> m[1] = 2
>>> id(m[1])
39356320 # new memory addres = different object!
>>> m = [[1]] * 3
>>> id(m[0])
40275408
>>> id(m[1])
40275408
>>> m[1][0] = 2
>>> id(m[1])
40275408 # same memory address = still the same object!
因此,在你看来,可能的工作是启动这样的矩阵:
>>> matrix = [[0 for i in range(3)] for j in range(2)]
>>> matrix
[[0, 0, 0], [0, 0, 0]]
>>> matrix[0][2] = 1
>>> matrix
[[0, 1, 0], [0, 0, 0]]
另一种更为激进的办法是完全转向numpy,其速度较快,从地面推向极快的矩阵和多层面病媒操纵,但使用也比较困难。
HTH!