如何解决Python中TypeError: int与dict_values不支持/运算的错误
错误原因与修复方案
错误原因
你遇到的TypeError是因为代码中sum(rawResult[0].value.counts.values())未返回预期的整数,导致你尝试用整数除以dict_values对象(而非其求和结果)。大概率是Classiq返回的counts结构和你预期的标准字典不同,或者sum的调用方式需要调整。
修复步骤
1. 先确认counts的结构
在计算期望前添加调试代码,明确counts的类型和内容:
countS = rawResult[0].value.counts print("counts类型:", type(countS)) print("counts内容:", countS) print("counts的值:", countS.values())
运行后查看输出,确认counts是否为标准字典,以及其值是否为可直接求和的整数。
2. 修正期望计算代码
根据counts的实际结构调整求和方式:
- 如果
counts是标准字典且值为整数,直接确保sum正确执行:total_counts = sum(countS.values()) Real_Expectation_Value = (2 * countS["0"] / total_counts) - 1 - 如果
counts的值是带数值属性的自定义对象,需要提取数值后求和:total_counts = sum(v.value for v in countS.values()) Real_Expectation_Value = (2 * countS["0"].value / total_counts) - 1
3. 修复执行偏好未生效的问题
你的代码中设置了执行偏好,但后续合成和执行时用的是原始quantumModel,导致num_shots等参数未生效。修正这部分代码:
for numShots in NumShots: quantumModel = create_model(main) # 设置执行偏好 quantum_model_with_preferences = set_execution_preferences( quantumModel, ExecutionPreferences( num_shots=numShots, job_name="Hadamard Test", random_seed=767 ) ) # 使用带偏好的模型合成 synthesized_model = synthesize(quantum_model_with_preferences) # 执行合成后的模型 rawResult = execute(synthesized_model).result() countS = rawResult[0].value.counts # 计算期望(用上面修正后的代码) total_counts = sum(countS.values()) Real_Expectation_Value = (2 * countS["0"] / total_counts) - 1 # 将结果存入列表 RealExpect.append(Real_Expectation_Value)
额外提示
- 确保
main函数是正确定义的量子电路入口,否则create_model(main)会生成无效模型。 - Python 3中
/会返回浮点数,符合量子期望的计算需求,无需额外转换。
内容的提问来源于stack exchange,提问作者sara00
相关产品推荐
相关产品推荐

