#list索引超出范围
问题描述:
def isexact(pat):
for c in pat.upper():
if c not in 'ATGC':
return 0
return 1
def print_matches(ofh, enz, matches):
if matches:
print >>ofh, "Enzyme %s matches at:" % enz,
for m in matches:
print >>ofh, m,
print >>ofh
else:
print >>ofh, "No match found for enzyme %s." % enz
def get_site_only(pat):
newpat = ""
for c in pat:
if c.isalpha():
newpat += c
return newpat
def findpos(seq, pat):
matches = []
current_match = seq.find(pat)
while current_match != -1:
matches.append(current_match)
current_match =seq.find(pat, current_match+1)
return matches
seq = ""
ifh = open("C:\Python27\\link_cutzymes.txt",'r')
ofh = open("C:\Python27\\re-en-output.txt", "w")
line = ifh.readline()
while line:
fields = line.split()
name = fields[0]
pat = get_site_only(fields[2])
if isexact(pat):
print_matches(ofh, name, findpos(seq, pat))
line = ifh.readline()
else:
line = ifh.readline()
ofh.close()
ifh.close()
它显示列表索引错误可以帮我#list索引超出范围
Traceback (most recent call last): File "C:/Users/ram/Desktop/rest_enz7.py", line 55, in name = fields[0] IndexError: list index out of range
答
name = fields[0]
- 你可能正在阅读的空行,分裂它,并在索引0,这是访问它超出范围的空列表。
您可以确保文件仅包含格式的行,检查代码中的空行,或使用try
和except
来命名几个选项。
答
从文件读取数据时,如果不存在要分割的数据,则不会转换为列表。我可以在您的代码中看到name = fields [0]正在导致错误。
那时请使用try和除了你的代码。
你可以重写代码:
try:
fields = line.split()
name = fields[0]
except:
pass
答
一个string[x]
做什么是获取列表的第x号。这意味着如果在第x个位置没有对象,那么你会得到一个错误。 因此,如果name = fields[0]
返回一个错误,那么fields
必须是一个空的列表(它看起来像这样:[]),因为没有第一个对象(Python从零开始计数,所以字母0是字母1,字母1是字母2等等)。你可以用try:
和except:
像这样解决这个问题:
try:
name = fields[0]
except:
name = '' #Or whatever code you want to run if it fails
在name = fields[0]
的发生在这里的好处是,你不会在代码中显示的线得到一个错误。或者,也许错误地复制了。 – Korem 2014-10-02 13:40:40
请复制粘贴你的实际代码。 – WeaselFox 2014-10-02 13:41:37