字典的倒数问题

0 投票
2 回答
45 浏览
提问于 2025-04-14 16:08

给定一个字典:weights = {"A":16, "B": 3, "C": 5},我想得到这些值的倒数。

输出应该是:weights_dict_reci = {"A":0.0625, "B": 0.3333333, "C": 0.2}

到目前为止,我尝试过:

weights_dict_reci = {value: 1 / weights_dict[value] for value in weights_dict}

还有:

for key in weights_dict:
    weights_dict[key] = 1 / weights_dict[key]

每次我都会遇到这个错误:不支持的操作数类型:'int' 和 'function'

第一个问题:如何为字典的值计算倒数?

第二个问题:我代码中的这个错误是怎么回事?

谢谢!

2 个回答

1

在你的 最小可复现示例 中,你的字典是 weights

你可以试试:

weights = {"A":16, "B": 3, "C": 5}

{k:1/v for k,v in weights.items()}

另外,正如你在尝试中所做的:

{value: 1 / weights[value] for value in weights}  # here value is the `key` for the dictionary `weights`. 

输出结果

#{'A': 0.0625, 'B': 0.3333333333333333, 'C': 0.2}

我不太确定 weights_dict 是什么,因为你没有提供相关信息。

从错误信息来看,似乎 weights_dict[value] 在你的代码中是一个函数。

1

在我用的Python版本上,下面的代码看起来运行得很好(不过你在提问的开头就有语法错误)。

weights_dict = {"A":16, "B": 3, "C": 5}
weights_dict_reci = {value: 1 / weights_dict[value] for value in weights_dict}
print( weights_dict )
print( weights_dict_reci )

输出结果:

{'A': 16, 'B': 3, 'C': 5}
{'A': 0.0625, 'B': 0.3333333333333333, 'C': 0.2}

撰写回答