简体   繁体   中英

How could I solve this error please (IndexError: list index out of range)?

I have the following work in Python. I'm trying to solve an equation by using Python and showing the results by plotting it. When I run my following below code, I got this error below:

The error:

Traceback (most recent call last):
  File "C:\Users\raineen\Desktop\Raneen_Python\Sigma_theta_c.py", line 44, in <module>
    segma.append((((Tt*Ct[count])/(2*t0*lambda1))*((m.log(item*r))**Nt[count]))+(((Tb*Cb)/(2*t0*lambda1))*((m.log(item*r))**Nb))+((Tt*Ct[count])/(t0*lambda1*(Nt[count]+1)))*((m.log(item*r))**(Nt[count]+1)-(m.log(item*R0))**(Nt[count]+1))+ ((Tb*Cb)/(t0*lambda1*(Nb+1)))*((m.log(item*r))**(Nb+1)-(m.log(item*R0))**(Nb+1)))
IndexError: list index out of range

I have three lists and I'm looping through them at the same time, they are:

t = [x/100 for x in range(1, 201)] # [0.01,0.02,0.02,..........,2]

Ct=  [126.0, 127.82549463360013, 129.67743712955985, 131.55621066590138, 133.46220397215035, 135.39581140976628, 137.35743305373825, 139.34747477536274, 141.36634832622116, 143.41447142337327]

a=  [39.960039960039964, 19.960079840319363, ..........]

Could I get any help to fix this problem, please?

The Python

import math as m
import matplotlib.pyplot as plt

lambda1 = 1
t = [x/100 for x in range(1, 201)]
t0 = 2
Tt = 1.5
Kt = 126
Kb = 1261
Rt = 5
Nt = [x/10 for x in range(0, 10)]
Nb = 0.36
Tb = 0.5
r = 6.5


R0 = Rt + t0
z = 2/m.sqrt(3)
#Ct = Kt*(z**Nt)
Cb = Kb*(z**Nb)


print('t= ', t)
print('Nt= ', Nt)
Ct = []
for n in Nt:
    Ct.append(Kt*(z**n))

Rm = []
for j in t:
    Rm.append(5+(j/2))

print('Rm= ',Rm)
print('Ct= ',Ct)

a = []
for k,i in zip(Rm,t):
    a.append(t0/(k*i))
    print(k, i)
print('a= ',a)

segma = []
for count, item in enumerate(a):
    segma.append((((Tt*Ct[count])/(2*t0*lambda1))*((m.log(item*r))**Nt[count]))+(((Tb*Cb)/(2*t0*lambda1))*((m.log(item*r))**Nb))+((Tt*Ct[count])/(t0*lambda1*(Nt[count]+1)))*((m.log(item*r))**(Nt[count]+1)-(m.log(item*R0))**(Nt[count]+1))+ ((Tb*Cb)/(t0*lambda1*(Nb+1)))*((m.log(item*r))**(Nb+1)-(m.log(item*R0))**(Nb+1)))

print('Sigma_theta_c = ', segma)

##for i in segma:
##    print(i)

plt.plot(t,segma)

plt.xlabel('t')
plt.ylabel('Sigma_theta_c')


plt.show()

This is below the equation:

在此处输入图片说明

我检查你的代码和问题是长度CtNt阵列是10 ,而名单的长度a是200。在这种情况下你列举的清单a使用count来访问列表元素CtNt这导致IndexError

General way to solve similar problems like this - check out length of the lists you are accessing, creating. Could you share full equations and your domain model? What exactly are you solving? What's the desired input and output?

len(t) # 200

len(segma) # 10

plt.plot(segma) works and actually creates the plot

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM