简体   繁体   中英

Python - index out of range

Trying to adapt a basic profiler for bash scripts, block of code below.

Can't figure out why profiling code with a "if branch" throws exception (for example when running this code with a duplicate file). 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

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 :

["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.

Maybe you meant results[i] ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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