check if a certain field is the same as desired

2

I would like to check if a particular field in a list is equal to == "Open"

            def mostrar():
            with open("ficheiro2.txt") as arquivo:
                i=0
                for linha in arquivo:
                    linha = eval(linha)
                    if linha[i][2]=="Aberta":
                        i=i+1
                        print (linha)
        mostrar()   

the file contains

[['teste', '02-01-19', 'Aberta'],['teste2', '02-01-19', 'Aberta'],['teste3', '02-01-19', 'Fechada']]

and wanted to check if the 2 field of the list that is inside another list is="Open" if it will show all that are equal

My output so far has been

[['pedrito', '02-01-19', 'Aberta'], ['pedrito', '02-01-19', 'Aberta'], ['pedrito', '02-01-19', 'Fechada']]

But it should be

[['pedrito', '02-01-19', 'Aberta'], ['pedrito', '02-01-19', 'Aberta']]
    
asked by anonymous 02.01.2019 / 14:57

1 answer

2

You're getting a different result because the algorithm you're using does not do what you're after.

In the code, you check whether the sublist of position i , at position 2, has the value "Aberta" . However, if this is true, instead of printing a list that only has those sublists that are "open," you print all sublists , including those "are closed".

And as @Anderson commented (and answered the other question), instead of using eval , you can use json.loads to get the lists, or sublists , saved.

Finally, you do not need to write this whole code, you can simplify it, like this:

def mostrar(): 
    with open("ficheiro2.txt") as arquivo:
         print([l for l in json.load(arquivo) if l[2] == "Aberta"]) 
mostrar()

That is, you print a list that stores each sublist from the main list, which has the value "Open" at position 2.

I hope I have helped!

    
02.01.2019 / 16:04