[英]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.