简体   繁体   English

Python - 索引超出范围

[英]Python - index out of range

Trying to adapt a basic profiler for bash scripts, block of code below.尝试为 bash 脚本调整基本分析器,下面是代码块。

Can't figure out why profiling code with a "if branch" throws exception (for example when running this code with a duplicate file).无法弄清楚为什么使用“if branch”分析代码会抛出异常(例如,在使用重复文件运行此代码时)。 From what I've traced, it somewhere creates an extra index value.根据我的追踪,它在某处创建了一个额外的索引值。 My apologies if this is trivial as I'm new to Python, but any suggestions on where could be the issue or how to remedy it would be greatly appreciated如果这是微不足道的,因为我是 Python 的新手,我深表歉意,但是对于问题出在哪里或如何解决它的任何建议,我们将不胜感激

def collect_timings(profiled_line, i):
    if i == len(results) - 1:
        return [0] + profiled_line
    timing = float(results[i+1][1].replace(".N", "")) - float(profiled_line[1].replace(".N", "")) 
    return [timing] + profiled_line

Error:错误:

Traceback (most recent call last):
  File "./profile", line 67, in <module>
    main(sys.argv)
  File "./profile", line 51, in main
    profiling_time = map(collect_timings, results, range(len(results)))
  File "./profile", line 24, in collect_timings
    timing = float(results[i+1][1].replace(".N", "")) - float(profiled_line[1].replace(".N", ""))
IndexError: list index out of range

Found the answer, posting in case it proves useful for someone.找到答案,张贴以防对某人有用。 The issues was a with a output redirection:问题在于输出重定向:

echo "Found '$file' is a duplicate of '${filecksums[$cksum]}'" >&2 

That got passed as a separate entry to results :这作为一个单独的条目传递给results

["Found 'txt2/0122file.bck' is a duplicate of 'txt2/0113file.txt'\n"]

No idea how to make the code run with redirects, but it's not necessary, so I'll just avoid it.不知道如何使代码与重定向一起运行,但这不是必需的,所以我会避免它。

you say:你说:

if i == len(results) - 1:

below you say:下面你说:

timing = float(results[i+1][1].replace(".N", ""))

so you check if "i" show the last element of results array (ie results has 5 cells from 0 to 4 and you check if i == 4 ( len(results) == 5 in this case AND NOT 4) ) and then you say results[i+1] which in the example above is equal to results[5] which is out of bounds.所以你检查“i”是否显示结果数组的最后一个元素(即结果有 5 个从 0 到 4 的单元格,你检查是否i == 4 (在这种情况下 len(results) == 5 AND NOT 4))然后你说results[i+1]在上面的例子中等于results[5]这是越界的。

Maybe you meant results[i] ?也许你的意思是results[i]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM