我正在尝试使用字典为python 2.7中的不同矩阵分配不同的键。
编辑 - 对于以前缺乏信息感到抱歉
以下是我的代码的完整实用示例:
import random
matrices_dict = {}
matrix = [[1,1],
[1,1],]
def checker(key_number):
for x in range(0, 2):
for y in range(0, 2):
matrix[x][y] = random.randint(0, 9)
matrices_dict[key_number] = matrix
print matrices_dict
checker(0)
checker(1)
...然后我看到生成的字典不存储生成的两个不同矩阵。相反,它使BOTH字典键1和2对应于第二个矩阵。
换句话说,它覆盖了第一个键的配对。这对我来说很奇怪,因为我很清楚地要求它只是将新矩阵写入新密钥。
关于如何让它不覆盖第一个键/矩阵配对的任何建议?
这里解决了什么
import random
matrices_dict = {}
def checker(key_number):
matrix = [[1,1],
[1,1],]
for x in range(0, 2):
for y in range(0, 2):
matrix[x][y] = random.randint(0, 9)
matrices_dict[key_number] = matrix
print matrices_dict
checker(0)
checker(1)
......我不清楚为什么第二个有效,第一个没有。在第一个中,为什么每次调用定义时都需要一个新矩阵?...为什么不覆盖先前创建的随机一个工作?
无论如何,为什么矩阵创建的任何细节都会影响词典是否会覆盖以前的密钥配对?
有兴趣知道出于好奇心!
答案 0 :(得分:1)
好的,所以想法是生成一个由(调用)矩阵引用的新对象,并在调用该函数时将引用(dict键)保存到这个新对象。例如:
import numpy as np
matrices_dict = {}
def checker(key_number):
# here we create a new object and add a reference
# (key in this case) to this new object to the dict.
# Note that each time this func is called, this line is executed
# and thus a new object is created
matrix = np.random.rand(1,2)
matrices_dict[key_number] = matrix
checker(1)
checker(2)
print(matrices_dict)
产生类似的东西:
{1: array([[ 0.33570685, 0.66721728]]), 2: array([[ 0.57074373, 0.62535056]])}
我们得到两个不同的矩阵,这看起来正是你想要的吗?
但是下一段代码出了什么问题。创建一个对象,每次调用该函数时,都会向该单个对象添加一个新引用。
import numpy as np
matrices_dict = {}
# here we create a single object
# Note that this line gets executed only once, so there is really
# just a single object that can be changed and referenced to.
matrix = np.random.rand(1,2)
def checker(key_number):
# add a new reference (key in this case) to the single object
# we created above to the dict
matrices_dict[key_number] = matrix
checker(1)
checker(2)
print(matrices_dict)
然后,当你描述它时,我们会得到错误的行为:
{1: array([[ 0.86548754, 0.92694858]]), 2: array([[ 0.86548754, 0.92694858]])}
关键是要理解参考和对象。创建列表时,您创建了一个最初由“矩阵”引用的对象。然后,当函数被调用时,以字典键的形式创建一个新的引用到同一个对象!因此,当您使用字典键或“矩阵”时,您最终访问并更改了同一个对象。