Search code examples
pythonfor-loopmatrixvectormultiplication

List Value Comparison - For loop iteration


I would like to compare item values. If they are equal, I want to print "true", otherwise I want to print "false". My code writes the results.

My result "prediction_list" in which I compare the values of 2 lists(test_labels and my_labels) should have a size of 260 because my original lists(test_labels and my_labels) have the size of 260. However, my prediction_list have the size of 67600 because of the for loop iteration. How should I correct it?

prediction = []

for i in test_labels:
    for item in my_labels:
        if item == int(i):
            prediction.append("true")
        else:
            prediction.append("false")

print prediction

Sample inputs and output:

NB Classifier labels in test set: [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

test_labels: ['0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n']

prediction: ['false', 'false', 'false', 'true', 'false', 'false', 'false', 'true', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false'...]


Solution

  • I agree with @MarkPython, but there's a slightly cleaner syntax.

    prediction = []
    
    for i in range(len(test_labels)):
        if test_labels[i] == my_labels[i]:
            prediction.append("true")
        else:
            prediction.append("false")