所以我在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()我确保在迭代主列表时修改复制的列表,所以这不可能是问题所在。
感谢任何帮助,谢谢:)
发布于 2015-04-01 15:32:54
您仅复制了对列表的引用。如果您想创建一个单独的列表副本,请使用slices:list2 = list1[:]或查看deepcopy模块。
发布于 2015-04-01 15:34:14
当您弹出时,数组大小会减小。这意味着如果列表的长度是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_list1i中。
你可以在列表理解中很容易做到这一点。
with open("membrane_GO.txt","r") as f:
lines = [line for line in f.readlines() if "Reactome" not in line]
print lines发布于 2015-04-01 15:36:58
假设你的列表最初是'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
https://stackoverflow.com/questions/29385154
复制相似问题