Home > OS >  How to round inside a list using f string
How to round inside a list using f string

Time:01-27

I want to round some numbers inside of a list by using f-string, but it returns

unsupported format string passed to list.__format__

This is my code

IS_gradebooks = [['ISOM2020', [59, 100, 80, 55, 95, 87, 95, 98, 74, 69, 92, 94, 75, 97, 43, 57]],
                 ['ISOM3400', [98, 73, 45, 88, 72, 94, 82, 100, 89, 52]], 
                 ['ISOM3600', [24, 44, 100, 81, 91, 93, 87, 72, 55]],
                 ['ISOM4200', [90, 56, 78, 67, 90, 93]]
                ]
bruh=IS_gradebooks
for i in range(len(bruh)):
  a=sum(bruh[i][1])/len(bruh[i][1]) 
  bruh[i][1]=a
print(f"{bruh:.2f}")

CodePudding user response:

You can change the variable bruh[i][1] to "{0:.2f}".format(a) and print that variable inside the loop:

for i in range(len(bruh)):
  a=sum(bruh[i][1])/len(bruh[i][1]) 
  bruh[i][1]="{0:.2f}".format(a)
  print(bruh[i])

CodePudding user response:

When you try to use f-strings to format a list, the format method of the list object is called, which is not implemented to handle formatting expressions. Therefore, python raises the error "unsupported format string passed to list.format".

If you tried

for i in range(len(bruh)):
    a = sum(bruh[i][1]) / len(bruh[i][1])
    bruh[i][1] = a
    print(f'{bruh[i][0]}: {bruh[i][1]:.2f}')

you will still get

TypeError: unsupported format string passed to list.__format__

because the python interpreter is trying to call the format method of the list object with the format specifier .2f. However, the format method of the list object is not implemented to handle formatting expressions like .2f and it doesn't know how to format a list of numbers with that specification.

One way around is : Instead of using an f-string to format the entire list, you can use an f-string inside a for loop to format each individual element of the list. Here's an example of how you could do this:

for i in range(len(bruh)):
    a = sum(bruh[i][1]) / len(bruh[i][1])
    bruh[i][1] = round(a, 2)
    print(f"{bruh[i][0]}: {bruh[i][1]}")

You can also use a list comprehension instead of a for loop to achieve the same result

bruh = [[i[0], round(sum(i[1])/len(i[1]), 2)] for i in bruh]
print(bruh)
  • Related