[英]List index out of range error, but can't see why?
This is pretty simple, but I can't figure out why I'm getting the 'list index out of range' error. 这很简单,但是我无法弄清楚为什么出现“列表索引超出范围”错误。 I have a list called 'cycle_entries' and a list called 'rawdates' which both have a length of 132:
我有一个名为“ cycle_entries”的列表和一个名为“ rawdates”的列表,它们的长度均为132:
print len(cycle_entries)
print len(rawdates)
132
132
The output of this is also a list of length 132: 此输出也是长度为132的列表:
times = re.findall(dtdict['tx'], str(entries))
print len(times)
132
However, when I try to iterate from index [0] to [131] I'm getting an error. 但是,当我尝试从索引[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
I can't figure out why, because this works: 我不知道为什么,因为这可行:
test = rawdates[131]+re.findall(dtdict['tx'], str(entries))[131]
print test
Anyone know why it works normally but I get the error inside the loop? 任何人都知道为什么它可以正常工作,但是我在循环内收到错误?
Assuming your lists contains strings, you can use zip
function to iterate over both lists simultenously: 假设您的列表包含字符串,则可以使用
zip
函数同时遍历两个列表:
>>> 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
Note that both variables are computed before the for
loop. 请注意,两个变量都是在
for
循环之前计算的。 You can also use itertools.izip
which makes an iterator instead of a list. 您也可以使用
itertools.izip
而不是列表来制作迭代器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.