[英]List index out of range error
因此,我再次在python中得到列表索引超出范围的错误,并且我无法弄清楚出了什么问题。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
f1 = open("membrane_GO.txt","r")
new_list1 = f1.readlines()
new_list2 = new_list1
for i in range(len(new_list1)):
if "Reactome" in new_list1[i]:
new_list2.pop(i)
print new_list2
f1.close()
我确保在重复遍历主列表时,正在修改重复列表,所以这不会成为问题。
感谢任何帮助,谢谢:)
您只重复了对列表的引用。 如果要创建列表的单独副本,请使用slices: list2 = list1[:]
或查看deepcopy
模块。
弹出时,数组大小减小。 这意味着如果列表的长度为10,而pop(0)
则列表的长度为9。如果您的pop(9)
不存在,则将出现边界错误。
例:
>>> x = [0,1,2,3,4]
>>> print x, len(x)
[0,1,2,3,4], 5
>>> x.pop(0)
>>> print x, len(x)
[1,2,3,4], 4
这是您的情况的错误,因为您从0转到len(new_list1)。
我建议您采用的方法是创建一个新列表,其中“ Reactome”不在new_list1 [i]中。
您可以通过列表理解轻松地做到这一点。
with open("membrane_GO.txt","r") as f:
lines = [line for line in f.readlines() if "Reactome" not in line]
print lines
假设您的列表最初是['a','b','c'],
然后list1 = list2 = ['a', 'b', 'c']
然后对len(list2)
进行迭代,即3次,然后i
将取值0、1和2。
在每次迭代中,您将从list1
中删除一个元素。
i = 0
remove list1[0]
new list = ['b', 'c']
i = 1
remove list1[1]
new list = ['b']
i = 2
remove list[2] which does not exist.
这样您将获得index out of bound error
只需添加到TigerHawks答案中:
因为你只有复制引用(不在名单本身),当你pop()
的元素出来的new_list2
,你也删除new_list1
beceause他们是相同的列表都引用。
假设循环开始时 new_list1
中有'n'个元素。 它将运行“ n”次迭代。
假设您从new_list2
弹出new_list2
元素(同样也从new_list1
),那么当循环尝试访问列表的“ nth”个元素时,您将获得index out of range
错误包含“ n-1”个元素
为了使其正常工作,请使用切片来复制列表:
new_list2 = new_list1[:]
顺便说一句, for i in range(len(new_list1)):
我认为是非Python语言的。 一种更好的方法是使用枚举 :
for index, element in enumerate(new_list1):
if "Reactome" in element:
new_list2.pop(index)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.