Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert list comprehension to for loop in python

So I have this list comprehension line I need to convert to a for loop in python.
pred and exp are lists that have many different values in them. They are part of a data set of numbers and with machine learning the code is supposed to guess the number(but that is just background)

correct = [(p, e) for (p, e) in zip(pred, exp) if p != e]

Output: of correct

[(8, 2),
 (7, 2),
 (9, 8),
 (4, 0),
 (2, 8),
 (9, 7),
 (8, 9),
 (8, 9),
 (2, 8),
 (1, 8),
 (4, 9),
 (9, 4),
 (3, 8),
 (1, 8),
 (3, 9),
 (9, 5),
 (9, 5),
 (9, 7),
 (3, 8),
 (1, 8),
 (9, 7),
 (9, 7),
 (2, 8),
 (9, 7),
 (3, 9),
 (8, 2),
 (1, 8),
 (7, 3),
 (1, 8),
 (3, 8),
 (9, 7),
 (5, 9),
 (3, 8),
 (2, 8),
 (8, 1),
 (9, 1),
 (1, 2),
 (9, 5),
 (8, 2),
 (4, 5),
 (9, 5),
 (4, 6),
 (2, 3),
 (1, 8),
 (8, 2),
 (9, 3),
 (8, 2),
 (5, 3),
 (9, 5),
 (1, 8),
 (1, 8),
 (3, 9),
 (8, 2),
 (1, 9),
 (1, 9),
 (8, 1),
 (3, 8),
 (2, 7)]

I tried this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

correct = []
for (p, e) in zip(predicted, expected):
    if p != e:
        correct.append(p)
        correct.append(e)
print(correct)

But the output looks like this

[5, 3, 6, 8, 1, 4, 7, 9, 7, 3, 7, 8, 7, 9, 7, 4, 7, 9, 9, 8, 9, 8, 6, 8, 8, 2, 8, 2, 3, 8, 1, 8, 1, 2, 1, 8, 1, 8, 9, 5, 7, 9, 7, 9, 1, 8, 9, 5, 1, 8, 8, 2, 7, 2, 8, 9, 3, 8, 9, 5, 8, 9, 6, 3, 7, 9, 8, 6, 0, 2, 2, 8, 9, 5, 9, 5, 7, 4, 9, 5, 1, 8, 1, 8, 5, 9, 1, 2, 7, 4, 8, 2]

Any help would be appreciated, thanks

>Solution :

You want a list of tuples, but you get a list of numbers. The reason is that you are appending the numbers just as numbers, not as tuples.

Instead, do

if p != e:
  correct.append((p,e))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading