假设给定的大矩阵显示商店中的产品库存:

该矩阵由以下数据结构表示:
{'products': [['milk'],
['bread'],
['eggs'],
['tomatoes'],
['cucumbers'],
['nuts'],
['cheese'], ...],
'store_a': {0: 40,
1: 415,
5: 55,
6: 7},
'store_b': {1: 45,
3: 44,
5: 451,
6: 451},
'store_c': {0: 455, 4: 54}}也就是说,商店中产品的每个库存由products列表的索引来表示。例如,store_a中的牛奶库存是40。
目标是找到在商店中找到特定产品的概率。也就是说,获取以下矩阵:

需要编写一个函数来获取上面的数据结构,并返回相同的结构,只是显示的是概率计算而不是数量。
在上面的例子中,预期的结果是:
{'products': [['milk'],
['bread'],
['eggs'],
['tomatoes'],
['cucumbers'],
['nuts'],
['cheese'], ...],
'store_a': {0: 0.0773694390715667,
1: 0.802707930367505,
5: 0.106382978723404,
6: 0.0135396518375242},
'store_b': {1: 0.0454086781029263,
3: 0.0443995963673058,
5: 0.455095862764884,
6: 0.455095862764884},
'store_c': {0: 0.893909626719057,
4: 0.106090373280943}}应该记住,这可能是一个非常大的矩阵,因此计算需要高效。
发布于 2020-11-05 16:01:09
试一试:
input={'products': [['milk'],
['bread'],
['eggs'],
['tomatoes'],
['cucumbers'],
['nuts'],
['cheese'], ...],
'store_a': {0: 40,
1: 415,
5: 55,
6: 7},
'store_b': {1: 45,
3: 44,
5: 451,
6: 451},
'store_c': {0: 455, 4: 54}}
for i in input:
if i != "products":
sum=0
for j in input[i]:
sum=sum+input[i][j]
for j in input[i]:
input[i][j]/=sum
print(input)https://stackoverflow.com/questions/64693031
复制相似问题