求助:解决TypeError——np.sqrt传入dict类型参数报错
问题解决:TypeError在np.sqrt处理字典时触发
错误原因
你在循环里调用np.sqrt(sorted_probs),但sorted_probs是字典类型,np.sqrt仅支持对数值(整数、浮点数或numpy数组)计算平方根,无法直接处理字典,因此触发该错误。另外你已经通过count = sorted_probs.get(key, 0)获取了当前key对应的概率值,却未在后续逻辑中使用这个变量。
修正方案
将psi_out_norm.append(np.sqrt(sorted_probs))修改为psi_out_norm.append(np.sqrt(count)),这样就能针对每个key对应的概率值计算平方根,而非错误地传入整个字典。
修正后的完整代码
import numpy as np num_qubits = 2 sorted_probs = {'00': 0.1826131640519985, '01': 0.3015290853531944, '10': 0.3171301575715357, '11': 0.1987275930232714} all_possible_keys = [format(i, f'0{num_qubits}b') for i in range(2**num_qubits)] psi_out_norm = [] for key in all_possible_keys: count = sorted_probs.get(key, 0) # use 0 if the key is missing psi_out_norm.append(np.sqrt(count)) # 替换为当前key对应的概率值count
可选优化
如果想简化代码,可以用列表推导式替代循环:
psi_out_norm = [np.sqrt(sorted_probs.get(key, 0)) for key in all_possible_keys]
内容的提问来源于stack exchange,提问作者mchaudh4
相关产品推荐
相关产品推荐

