2017-09-06 110 views
0

这很简单,但我不明白为什么我得到'列表索引超出范围'的错误。我有一个名为“cycle_entries名单和名为“rawdates”,这两者都具有132的长度列表:列表索引超出范围错误,但看不到原因?

print len(cycle_entries) 
print len(rawdates) 
132 
132 

的这个输出也是长度的列表132:

times = re.findall(dtdict['tx'], str(entries)) 
print len(times) 
132 

然而,当我尝试从索引[0]迭代到[131]时,出现错误。

for i in range(len(cycle_entries)): 
    localtime = rawdates[i]+re.findall(dtdict['tx'], str(entries))[i] 
    print localtime 

IndexError: list index out of range 

我想不通为什么,因为这个工程:

test = rawdates[131]+re.findall(dtdict['tx'], str(entries))[131] 
print test 

任何人都知道为什么它工作正常,但我得到了循环内的错误?

+0

是'时,会发生什么样的价值i'错误?如果你在循环之外移动'findall'操作,错误是否会持续? – Sayse

+0

我不确定,但我尝试了0和131两个都在循环外工作。 –

+2

首先,你为什么要在循环中计算're.findall(dtdict ['tx'],str(entries))'?它没有改变。在循环开始前计算一次(如'times')并使用循环中的列表。 – DyZ

回答

0

假设你的列表中包含字符串,你可以使用zip功能两份名单simultenously遍历:

>>> times = ['1', '2', '3', '4'] 
>>> rawdates = ['raw1', 'raw2', 'raw3', 'raw4'] 
>>> for time, rawdate in zip(times, rawdates): 
    localt = time + rawdate 
    print localt 


1raw1 
2raw2 
3raw3 
4raw4 

注意这两个变量在for循环之前计算的。 您也可以使用itertools.izip来制作迭代器而不是列表。

Python's zip function docs

相关问题