-1

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

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

Reti43
  • 9,656
  • 3
  • 28
  • 44
  • Can you elaborate _why_ you need this as a for loop? It's perhaps irrelevant to the question, but maybe not – lucidbrot Dec 01 '21 at 22:13
  • 3
    In the code you tried, just replace the two `append` lines with a single one: `correct.append((p, e))` – Arne Dec 01 '21 at 22:14
  • As @Arne said, you want a LIST of TUPLES(p,e) not just individual append calls – troy Dec 01 '21 at 22:15

2 Answers2

3

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))
lucidbrot
  • 5,378
  • 3
  • 39
  • 68
1

Inside the for loop you're appending p and e to the list as single elements, despite the fact that on each iteration you get them inside a tuple.

To fix it just append them to the list as a tuple element.

if p != e:
    correct.append((p,e))
Momofil31
  • 11
  • 3