简体   繁体   中英

List index out of range - Python

I'm writing a short code (my first in python) to filter a large table.

import sys

gwas_annot = open('gwascatalog.txt').read()
gwas_entry_list = gwas_annot.split('\n')[1:-1]

# paste line if has value
for lines in gwas_entry_list:
    entry_notes = lines.split('\t')
    source_name = entry_notes[7]
    if 'omega-6' in source_name:
        print(entry_notes)

Basically I want to take the 'gwascatalog' table, parse it into lines and columns, search column 7 for a string ('omega-6' in this case) and if it contains it, print the entire line.

Right now it prints all the rows to the console but won't let me paste it into another file. It also gives me the error:

Traceback (most recent call last):<br>
  File "gwas_parse.py", line 9, in <module><br>
    source_name = entry_notes[7]<br>
IndexError: list index out of range

Unsure why there is an error. Anything obvious to fix?

Edit: Adding snippet from data.

在此输入图像描述

You can secure yourself by checking the length of the list first.

if len(entry_notes) > 7:
    source_name = entry_notes[7]

The list index out of range could be that you hit a row (line) where there are less than 7 columns.

    # index      0      1     2       3      4      5      6       (... no 7)
columnsArray = ['one', 'two','three','four','five','six', 'seven']

So here, if you ask for array[7], you get a "list index out of range" error because the line that the for loop is currently on only goes up to index 6.

The error tells you it happens at "line 9", which is where "source_name = entry_notes[7]". I would suggest printing out the number of columns for each row on the table. You might notice that somewhere you have 7 columns instead of 8. I also think you mean to say column 8, but position(or index 7), since counting in python starts at 0.

Maybe add another "if" to only look for lines that have a len() of 8 or more.

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