Search code examples
pythonarraysreplicationformat-specifiers

How to use same format specifer for array assginement or printing?


I have the following two arrays meanA and stdA. I want to combine them and generate a third array C.

meanA = [86.6,87.2,85.4,86.6,83.0,87.2,92.7,80.0,86.6,87.8,89.0,87.8]
stdA = [0.08, 3.1,0.08,2.5,0.1,3.1,1.2,0.4,1.2,1.2,0.0,3.7]

I want to combine these two arrays using a format specifier as "%.2f+/-%.2f%%" and generate a third array C. I am writing it in python as C = "%.2f+/-%.2f%%" % (meanA , stdA). But, this is giving me an error as TypeError: only size-1 arrays can be converted to Python scalars.

I know this operation can be possible only on scalars. But, I want to know can we do this on arrays as well. I want to avoid writing the same line multiple times as below.

C[0] = "%.2f+/-%.2f%%" % (meanA[0] , stdA[0]) C[1] = "%.2f+/-%.2f%%" % (meanA[1] , stdA[1]) C[2] = "%.2f+/-%.2f%%" % (meanA[2] , stdA[2]) C[3] = "%.2f+/-%.2f%%" % (meanA[3] , stdA[3]) C[4] = "%.2f+/-%.2f%%" % (meanA[4] , stdA[4]) C[5] = "%.2f+/-%.2f%%" % (meanA[5] , stdA[5]) C[6] = "%.2f+/-%.2f%%" % (meanA[6] , stdA[6]) C[7] = "%.2f+/-%.2f%%" % (meanA[7] , stdA[7]) C[8] = "%.2f+/-%.2f%%" % (meanA[8] , stdA[8]) C[9] = "%.2f+/-%.2f%%" % (meanA[9] , stdA[9])

I want the following output C= [86.6+/-0.08, 87.2+/-3.1, 85.4+/-0.08, 86.6+/-2.5, 83.0+/-0.1, 87.2+/-3.1, 92.7+/-1.2, 80.0+/-0.4, 86.6+/-1.2, 87.8+/-1.2, 89.0+/-0.0, 87.8+/-3.7].

Does anyone know the simplest way to do this in a single line of code?

Thank you in advance!


Solution

  • Feed individual elements into a string converter:

    ["%.2f+/-%.2f%%" % (a, b) for a, b in zip(meanA, stdA)]
    

    Result:

    ['86.60+/-0.08%',
     '87.20+/-3.10%',
     '85.40+/-0.08%',
     '86.60+/-2.50%',
     '83.00+/-0.10%',
     '87.20+/-3.10%',
     '92.70+/-1.20%',
     '80.00+/-0.40%',
     '86.60+/-1.20%',
     '87.80+/-1.20%',
     '89.00+/-0.00%',
     '87.80+/-3.70%']
    

    It looks a bit cleaner with f-strings:

    [f'{a:.2f}+-{b:.2f}%' for a, b in zip(meanA, stdA)]