[英]How to fix “IndexError: list index out of range” in the following piece of code
I have been running the following code o Jupyter Notebook 5.7.4 with Python 3.7.1. 我一直在使用Python 3.7.1运行以下代码o Jupyter Notebook 5.7.4。 It worked fine there.
它在那里工作得很好。 When I tried to run the same code on HPC with python 3.5.2 I keep getting following error.
当我尝试使用python 3.5.2在HPC上运行相同的代码时,我不断收到以下错误。 if array[i-1] == array[i]: IndexError: list index out of range
如果array [i-1] == array [i]:IndexError:列表索引超出范围
import vcf
v = vcf.Reader(filename='/scratch/global/kkdesi01/Equine/animals/Chr/Chr11_possibleIntrogressionTargets.vcf')
f = open('/scratch/global/kkdesi01/Equine/animals/Chr/position11.txt', 'w+')
for record in v:
f.write(str(record.POS))
f.write('\n')
f.close()
with open('/scratch/global/kkdesi01/Equine/animals/Chr/position11.txt', 'r') as ins:
array = []
for line in ins:
array.append(line)
print(len(array))
f = open('/scratch/global/kkdesi01/Equine/animals/Chr/filter11.txt', 'w+')
for i in range (1, len(array)):
val1 = int(array [i-1])
val2 = int(array [i])
diff = val2-val1
if diff < 10:
f.write (str(val1))
f.write ('\n')
f.write (str(val2))
f.write ('\n')
f.close()
with open('/scratch/global/kkdesi01/Equine/animals/Chr/filter11.txt', 'r') as ins:
array = []
for line in ins:
array.append(line)
len(array)
for i in range(1, len(array)):
if array[i-1] == array[i]:
del array[i]
error if array[i-1] == array[i]: IndexError: list index out of range 如果array [i-1] == array [i]则出错:IndexError:列表索引超出范围
I need help in understanding what needs to be changed in the code 我需要帮助来理解代码中需要更改的内容
See below what is the problem. 看下面是什么问题。
You modify the length of the array during the iteration. 您可以在迭代期间修改数组的长度。
User set in order to remove duplicates. 用户设置以删除重复项。
array = [2, 3, 4, 4, 4]
for i in range(1, len(array)):
if array[i - 1] == array[i]:
print('Remove entry at offset {}'.format(i))
del array[i]
output 产量
Remove entry at offset 3
if array[i - 1] == array[i]:
IndexError: list index out of range
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.