我想通过linalg.solve(A,b)求解方程组,解决线性矩阵方程或来自scipy.org的线性标量方程组。具体来说,我有两个字典,dict1和dict1,为了使用上面的脚本,我需要将它们转换为矩阵。从字典中创建一定大小的矩阵
food = ['fruits', 'vegetables', 'bread', 'meat']
frequency = ['daily', 'rarely']
consumptions = {'fruits': {'daily': 6, 'rarely': 4}, 'vegetables': {'daily': 8, 'rarely': 6}, 'bread': {'daily': 2, 'rarely': 1}, 'meat': {'daily': 2, 'rarely': 1}}
dict1 = {}
for f in food: #type of food
for j in food:
dict2 = {}
total = 0.
for q in frequency:
dict2.update({q:(consumptions.get(j).get(q)*consumptions.get(f).get(q))})
key = f+'v'+j #comparing the different foods
dict1.update({key:dict2})
这给了我:
{'breadvbread': {'daily': 4, 'rarely': 1},
'breadvfruits': {'daily': 12, 'rarely': 4},
'breadvmeat': {'daily': 4, 'rarely': 1},
'breadvvegetables': {'daily': 16, 'rarely': 6},
'fruitsvbread': {'daily': 12, 'rarely': 4},
'fruitsvfruits': {'daily': 36, 'rarely': 16},
'fruitsvmeat': {'daily': 12, 'rarely': 4},
'fruitsvvegetables': {'daily': 48, 'rarely': 24},
'meatvbread': {'daily': 4, 'rarely': 1},
'meatvfruits': {'daily': 12, 'rarely': 4},
'meatvmeat': {'daily': 4, 'rarely': 1},
'meatvvegetables': {'daily': 16, 'rarely': 6},
'vegetablesvbread': {'daily': 16, 'rarely': 6},
'vegetablesvfruits': {'daily': 48, 'rarely': 24},
'vegetablesvmeat': {'daily': 16, 'rarely': 6},
'vegetablesvvegetables': {'daily': 64, 'rarely': 36}}
我想,因为我使用的4种类型的食物,这种转换为4×4矩阵。我没有把dict2作为一次我想出如何用一本字典转换为矩阵,我可以做另一个,但如果你需要它,我可以更新。
我是新来的Python,想玩玩字典和矩阵求解:)。使用数组很容易,但是现在我想看看如果我有字典,该怎么办。
你能举一个例子来理解你的意思吗?将它转换为4x4矩阵?你试图解决什么系统? –
在进行排列组合时,应考虑使用“V”或下划线以提高可读性。 – kmario23