【发布时间】:2017-10-05 08:10:53
【问题描述】:
运行此代码时出现索引超出范围错误。如果 tmp > 3 并且如果 tmp[2] == tmp[3] 则有效。满足条件时,我试图将 index[0] 中的数字写入文件。又名 tmp[0] == tmp[1]。为什么无论我尝试了什么,我都无法调用 tmp[0]。
i = 0
tmp = []
while(i < len(sequence)):
tmp = sequence[i].replace("(","").replace(")","").split(",")
if(len(tmp) > 1):
if(tmp[0] == tmp[1]):
print tmp[0]
with open(output_file1, 'a') as output:
output.write(str(tmp[0]) + '\n')
i = i+1
return True
python app.py
Traceback (most recent call last):
File "app.py", line 71, in <module>
generate(6, out_path2,out_path1, out_path)
File "app.py", line 45, in generate
random6th = random.choice(sequence2).replace("[", "").replace("]","").replac
e("'","").replace(" ","")
File "C:\Python27\lib\random.py", line 275, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq is emp
ty
IndexError: list index out of range
i = 0
tmp = []
while(i < len(sequence)):
tmp.append(sequence[i].replace("(","").replace(")","").split(","))
if(len(tmp) > 0):
if(tmp[0] == tmp[1]):
print tmp[0]
with open(output_file1, 'a') as output:
output.write(str(tmp[0]) + '\n')
i = i+1
return True
Traceback (most recent call last):
File "app.py", line 69, in <module>
generate_2(seq_path, out_path1, out_path2);
File "app.py", line 20, in generate_2
if(tmp[0] == tmp[1]):
IndexError: list index out of range
使用第二个代码,我在 if(tmp[0] == tmp[1] 处遇到另一个回溯错误 使用 PRINT tmp[0],从不运行上述错误的第二个代码回溯。
一个序列看起来像这样
(8, 16, 5, 5, 65, 27)
(7, 15, 4, 4, 64, 26)
(21, 17, 12)
(22, 22, 11, 11, 59, 24)
(21, 21, 10, 9, 58, 23)
我正在尝试匹配 21 和 21 tmp[0] == tmp[1],然后写入文件 21。
【问题讨论】:
-
你能分享一下确切的回溯吗?
-
你也可以在分配后给我们一个
print(tmp)的输出吗? -
sequence[i].replace("(","").replace(")","").split(",")看起来像穷人的ast.literal_eval -
什么是
index[0]? (您也不要在循环中的任何地方更改i。) -
index[0] 是 6 位数字列表中的一个数字,例如 1 2 3 4 5 6,其中 1 是 index[0]
标签: python python-2.7 indexing