当我运行这段代码时,出现错误,我不明白问题出在哪里。 该代码的工作方式类似于(getx)创建系统数组时,Cost,weight和expression函数根据(getx)数组开始计算。误差下,数组W是Weight,C是Cost,R是Reliability。
错误是:
>IndexError Traceback (most recent call last)
<ipython-input-4-0ce5705f90fb> in <module>
76 if char!= 0 :
77 exp = expression(R , possition , char)
---> 78 wei = Weight(W , possition , char)
79 cost = Cost(C , possition , char)
80 Total = Total* exp
<ipython-input-4-0ce5705f90fb> in Weight(W, possition, char)
54 def Weight(W , possition , char):
55 expW = 0
---> 56 expW = expW + W[possition][int(char)]
57 return expW
58
>IndexError: list index out of range
我的代码:
import random
def getsys():
row = ''
for i in range(0 , 8):
randintt = str(random.randint(0 , 3))
row += randintt
return row
def getx():
x = []
for i in range(0,14):
mysys = getsys()
x.append(mysys)
return x
y = getx()
print (y)
import initialsys
import numpy as np
R = np.array([[0.90 , 0.93,0.91 , 0.95],
[0.95 , 0.94, 0.93, 0],
[0.85 , 0.90 , 0.87 , 0.92],
[0.83 , 0.87 , 0.85 , 0 ],
[0.94 , 0.93 , 0.95 , 0],
[0.99 , 0.98 , 0.97 , 0.96],
[0.91 , 0.92 , 0.94 , 0],
[0.81 , 0.90 , 0.91 , 0],
[0.97 , 0.99 , 0.96 , 0.91],
[0.83 , 0.85 , 0.90 , 0],
[0.94 , 0.95 , 0.96 , 0],
[0.79 , 0.82 , 0.85 , 0.90],
[0.98 , 0.99 , 0.97 , 0],
[0.85 , 0.92 , 0.95 , 0.99]
])
C = np.array([[1, 1, 2, 2],
[2, 1, 1, 0],
[2, 3, 1, 4],
[3, 4, 5, 0],
[2, 2, 3, 0],
[3, 3, 2, 2],
[4, 4, 5, 0],
[3, 5, 6, 0],
[2, 3, 4, 3],
[4, 4, 5, 0],
[3, 4, 5, 0],
[2, 3, 4, 5],
[2, 3, 2, 0],
[4, 4, 5, 6]
])
W = np.array([[3,4,2,5],
[8,10,9,0],
[7,5,6,4],
[5,6,4,0],
[4,3,5,0],
[5,4,5,5],
[7,8,9,0],
[4,7,6,0],
[8,9,7,8],
[6,5,6,0],
[5,6,6,0],
[4,5,6,7],
[5,5,6,0],
[6,7,6,9]
])
def expression(r ,possition , char ):
exp=1-r[possition , int(char)]
return exp
def Weight(W , possition , char):
expW = 0
expW = expW + W[possition][int(char)]
return expW
def Cost (C , possition , char):
expC = 0
expC =expC + W[possition][int(char)]
return expC
T = []
W = []
C = []
for z in range(1000):
x = initialsys.getx()
possition = 0
Total = 1.0
char = ""
TotalC = 0
TotalW = 0
for row in x :
for char in row :
if char!= 0 :
exp = expression(R , possition , char)
wei = Weight(W , possition , char)
cost = Cost(C , possition , char)
Total = Total* exp
TotalC = TotalC + cost
TotalW = TotalW + wei
Total = 1-Total
end = 1
end = Total * end
possition = possition + 1
T.append(end)
W.append(TotalC)
C.appaend(TotalW)
print(T)
该问题该怎么办??? :(
答案 0 :(得分:0)
快速复制您给出的示例并运行它。问题出现在此行的第一个迭代中:
expW = expW + w[possition][int(char)]
您将获得IndexError
的位置。问题在于您将W
初始化为空列表,并传递给函数Weight
,在该函数中您尝试访问上述内容(不存在)。
所以我不知道您的代码到底能做什么,但是您(很具体地)首先初始化W
并随后用一个空列表替换它似乎很奇怪。也许有一些错误。