Home > Back-end >  Someones know a better option to print this variables?
Someones know a better option to print this variables?

Time:09-22

I'm looking for print some variables more quickly. The code that i'm using is:

A_PR=3
B_PR=4
C_PR=6
print('the value of the model A is:', A)
print('the value of the model B is:', B)
print('the value of the model C is:', C)

I was thinking in a loop with a the for, but I couldn't make it work.

CodePudding user response:

You can use string formatting like this:

A_PR=3
B_PR=4
C_PR=6

print('Model A: {} \nModel B: {}\n Model C: {}'.format(A_PR, B_PR, C_PR))

Or you could embed those values into a array and loop over that array. Using ASCI values you can print A - Z model results

A_PR=3
B_PR=4
C_PR=6
model_results = [A_PR, B_PR, C_PR]

for idx, result in enumerate(model_results):
    print('Model {}: {}'.format(chr(idx   65), result))

Output:

Model A: 3
Model B: 4
Model C: 6

CodePudding user response:

    model_dict = {'A':3, 'B':4, 'C':6,}
    for k,v in model_dict.items():
        print(f"the value of model {k} is: {v}")

Here's a simple solution I whipped up using python f strings and a dictionary

CodePudding user response:

If you really want to do this, you would have to access those variables by names that are stored in another variable. Some people call it "dynamic variable names". One option, once again if you really want to do it, is to use globals():

for x in ['A', 'B', 'C']:
    print(f'The value of the model {x} is:', globals()[x   '_PR'])

# The value of the model A is: 3
# The value of the model B is: 4
# The value of the model C is: 6

But it is not recommended: see How do I create variable variables?.

So one of better options might be to use an iterable data type, such as dict:

models = {'A': 3, 'B': 4, 'C': 6}

for x in ['A', 'B', 'C']:
    print(f'The value of the model {x} is: {models[x]}')

It can be further simplified using items, although I am not a huge fan of this, if I want to preserve the order.

models = {'A': 3, 'B': 4, 'C': 6}

for k, v in models.items():
    print(f'The value of the model {k} is: {v}')

(A dict does preserve the order, but in my mind, I treat dict as not being ordered conceptually).

CodePudding user response:

Something like this should work as a small dictionary with a for loop. Simply unpack keys and values.

PR = {
    "A_PR": 3, "B_PR" :4 , "C_PR":6,
}

for k,v in PR.items():
    print(f'the value of the model {k} is: {v}')
  • Related