Home > OS >  How i do a print for a specific variable in a loop? [duplicate]
How i do a print for a specific variable in a loop? [duplicate]

Time:09-23

i'm looking to print the an specific name and the result of a function that a i did. I'm using this code:

arrays=[qda_confusion_matrix, Knn_5_confusion_matrix, Tree_Boo_confusion_matrix]
names=['QDA', '5-NN', 'Tree con Boosting']
for name in names:
    for array in arrays:
        print(name,'\n')
        Spe=Specificity(array)

As you can see, I want to do the function Specificity(array) in each of the arrays that the variable arrays has. Nevertheless, I also want that for the fist array, that in this example is qda_confusion_matrix appear the name of the model, that is QDA and then the result.

The result from this code is:

QDA 

Specificity: 0.235
QDA 

Specificity: 0.059
QDA 

Specificity: 0.306
5-NN 

Specificity: 0.235
5-NN 

Specificity: 0.059
5-NN 

Specificity: 0.306
Tree con Boosting 

Specificity: 0.235
Tree con Boosting 

Specificity: 0.059
Tree con Boosting 

Specificity: 0.306

This result is wrong because what i want is:

QDA
Specificity: 0.235

5-NN
Specificity: 0.059

Tree con Boosting
Specificity: 0.306

CodePudding user response:

You need zip() to loop over both lists in parallel

arrays=[qda_confusion_matrix, Knn_5_confusion_matrix, Tree_Boo_confusion_matrix]
names=['QDA', '5-NN', 'Tree con Boosting']

for value, name in zip(arrays, names):
    print(name)
    Spe = Specificity(value)
  • Related