Python新手求助:访问字典内嵌套列表触发索引越界错误
解决IndexError及绘图问题
错误原因分析
先看你提供的data_d里,q_sol和cl_sol的实际结构:
q_sol是两层嵌套的列表:外层列表只有1个元素(只能用索引0访问),这个元素又是一个列表,里面也只有1个元素(同样用索引0访问),才是你要的量子解数组。cl_sol是一层嵌套的列表:外层列表也只有1个元素(索引0),直接就是经典解数组。
你设置的idx1=3,但这两个列表的长度都是1,根本没有索引3的元素,所以直接触发了IndexError: list index out of range。
修正后的代码
import matplotlib.pyplot as plt import numpy as np # 你的原始data_d数据 data_d= {'num_qubits': [3], 'obj_count': [[0]], 'circ_count': [[3372]], 'iter_count': [[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]], 'err': [[9.622750520686739e-05]], 'params': [[np.array([ 6.77857446, 8.45117651, 5.98536102, 6.77631199, 4.42401965, 8.78988251, 6.30550002, 10.77596014, 12.7089123 , 4.95594055, 9.14241059, 5.84989104, 8.40700518, 11.64485529, 0.81896469, 0.82775066, 0.36833961, 10.27488743, 10.09543112, 10.91158005, 12.3788683 , 9.96858319, 5.62269489])]], 'q_sol': [[np.array([ 0.62855239, 0.90343679, 0.82492677, 0.39294472, -0.39294322, -0.82492691, -0.90343593, -0.62855236])]], 'cl_sol': [np.array([ 0.62853936, 0.90352533, 0.82495791, 0.3928371 , -0.3928371 , -0.82495791, -0.90352533, -0.62853936])]} def plot_solution_vectors(q_sol, cl_sol): fig = plt.figure() ax = fig.add_subplot(111) # 修正拼写错误:qauntum → quantum ax.plot(q_sol, label='quantum', color='black') ax.plot(cl_sol, label='classical', color='black', linestyle='dashed') ax.legend() ax.set_xlabel('Node number') ax.set_ylabel('Components of solution') # 修正norm变量混淆:原代码赋值与文本描述颠倒 qnorm = np.linalg.norm(q_sol) cnorm = np.linalg.norm(cl_sol) ax.text(0.55, 0.65, f'Norm (quantum) = {qnorm:.1f}', transform=ax.transAxes) ax.text(0.55, 0.55, f'Norm (classical) = {cnorm:.1f}', transform= ax.transAxes) return fig, ax # 使用正确的索引取值 idx1, idx2 = 0, 0 q_sol = data_d['q_sol'][idx1][idx2] cl_sol = data_d['cl_sol'][idx1] fig, ax = plot_solution_vectors(q_sol, cl_sol) plt.show() # 添加显示图像的代码
额外修正说明
- 拼写错误:把
qauntum改成了正确的quantum - 变量混淆:原代码中量子解和经典解的范数变量赋值颠倒,已修正
- 补充
plt.show():确保绘制的图像能正常显示出来
内容的提问来源于stack exchange,提问作者mchaudh4
相关产品推荐
相关产品推荐

