Home > Mobile >  I want python to skip the list if it doesn't have more than 3 parts (space separated) while rea
I want python to skip the list if it doesn't have more than 3 parts (space separated) while rea

Time:07-15

I'm making python read one file that makes all the lines of a file as a space-separated list current I'm facing an issue where I want python to read a list only if the content is more than 3 parts I'm trying if int(len(list[3])) == 3: then read the 3 parts of the list but the program is giving the error of

`IndexError: list index out of range

it is usually given when I access something that doesn't exist but the line of code that read the 3rd part shouldn't run on a list without 3 parts

CodePudding user response:

You are probably looking for:

if len(list) > 3:
    # read list
  1. You don't need to convert len() to an int - it already is an int
  2. list[3] gives you back fourth element of the list, you need to pass whole list object to len function
  3. int == 3 will only catch numbers equal to 3, while you wanted all numbers above 3

CodePudding user response:

I think is this:


def get_file_matrix(file:str):
    with open(file,'r') as arq:
        lines = arq.readlines()
        #saniting 
        lines_clear = list(map(lambda line:line.strip(),lines))
        lines_splited = list(map(lambda line:line.split(' '),lines_clear))
        lines_filtered = list(filter(lambda line: len(line) <= 3,lines_splited    ) )
        return lines_filtered


r = get_file_matrix('test.txt')
print(r)
  • Related