IndexError:列表索引超出范围(Bloch球形)

时间:2018-11-13 02:51:28

标签: python-3.x quantum-computing

我正在尝试构建一个称为Bloch球的东西,它是单个量子位的3-D表示。目前,我正在创建一个沿x轴开发动画的函数,这是我编写的代码。

def x_animation(self):
    #Y and Z are inputs from users
    Y1 = self.Y*(-1)
    Z1 = self.Z*(-1)
    #number of dots which consists animation
    length = 10
    for i in range(length+1):
        # an array of X,Y,Z coordinates of 10 dots
        xgate= []
        xgate_y = np.linspace(self.Y,Y1,length+1)
        xgate_z = np.linspace(self.Z,Z1,length+1)
        xgate.append([self.X,round(xgate_y[i],1),round(xgate_z[i],1)])
        plot(xgate[i][0],xgate[i][1],xgate[i][2])

但是,我在下面看到了错误消息。

IndexError                                Traceback (most recent call last)
<ipython-input-5-f56aa4b3a487> in <module>()
----> 1 q.x_animation()

<ipython-input-3-f74dcce093d4> in x_animation(self)
 57             xgate_z = np.linspace(self.Z,Z1,length+1)
 58           xgate.append([self.X,round(xgate_y[i],1),round(xgate_z[i],1)])
---> 59             plot(xgate[i][0],xgate[i][1],xgate[i][2])
 60 
 61     def x_gate(self):

IndexError: list index out of range

如果有人帮助我解决这个问题,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

您的代码在每次迭代时都会将列表xgate初始化为一个空列表,然后将其附加一个元素,因此xgate到{{1 }} 叫做。但是plot尝试访问plot的第i个元素,该元素将在第一次迭代中成功,而在第二次迭代中失败(一次xgate)。

您应该能够通过将列表初始化i=1移到循环外来解决此问题,以便它实际上会积累元素。

(我不确定xgate = []xgate_y的初始化是否也应该在循环中,但是它们不是累积的,也不会引起这种问题。)