字典倒数的问题

问题描述 投票:0回答:1

给出的字典:

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'

第一个:如何使 tke 为 dict 值的倒数?

第二:我的代码中出现此错误的原因是什么?

谢谢!

python dictionary
1个回答
0
投票

你可以尝试:

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

{k:1/v for k,v in weights.items()}
© www.soinside.com 2019 - 2024. All rights reserved.