代码之家  ›  专栏  ›  技术社区  ›  mchaudh4

IndexError:访问字典中列表中的数据时,列表索引超出范围

  •  0
  • mchaudh4  · 技术社区  · 2 年前

    我正在与错误作斗争:

    in <module>
        q_sol = data_d['q_sol'][idx1][idx2]
    IndexError: list index out of range
    

    我正试图在 q_sol cl_sol 但不知何故,无法正确理解这些索引。 我是蟒蛇新手。如果能帮助我解决这个错误,我将不胜感激。

    The value of 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': [[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': [[array([ 0.62855239,  0.90343679,  0.82492677,  0.39294472, -0.39294322,
               -0.82492691, -0.90343593, -0.62855236])]], 'cl_sol': [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)
        ax.plot(q_sol, label='qauntum', 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')
        
        cnorm = np.linalg.norm(q_sol)
        qnorm = np.linalg.norm(cl_sol)
        
        ax.text(0.55, 0.65, 'Norm (quantum) = %.1f'%(qnorm), transform=ax.transAxes)
        ax.text(0.55, 0.55, 'Norm (classical) = %.1f'%(cnorm), transform= ax.transAxes)
        
        return fig, ax   
                    
    idx1, idx2 = 3, 0
    q_sol = data_d['q_sol'][idx1][idx2]
    cl_sol = data_d['cl_sol'][idx1]
    plot_solution_vectors(q_sol, cl_sol)
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Damian Satterthwaite-Phillips    2 年前

    如果你看 data_d['q_sol'] ,您可以看到该值为:

    [[array(
      [ 0.62855239,  0.90343679,  0.82492677,  0.39294472, -0.39294322,
       -0.82492691, -0.90343593, -0.62855236])]]
    

    所以 data_d['q_sol'][0] 是:

    [array(
      [ 0.62855239,  0.90343679,  0.82492677,  0.39294472, -0.39294322,
       -0.82492691, -0.90343593, -0.62855236])]
    

    data_d['q_sol'][0][0] :

    array(
        [ 0.62855239,  0.90343679,  0.82492677,  0.39294472, -0.39294322,
         -0.82492691, -0.90343593, -0.62855236])
    

    data_d['q_sol'][0][0][3] (我认为这是你真正想要的价值)是:

    0.39294472