Home > Software design >  How can I make an int to add each value of the matrix and add 20% with input
How can I make an int to add each value of the matrix and add 20% with input

Time:12-04

a = [ [200,300,5000,400],[554,500,1000,652],[800,500,650,800],[950,120,470,500],[500,600,2000,100]]


for i in range(len(a)):
    for j in range(len(a[i])):

        print(a[i][j], end=' ')
print()  

I am trying to increase each value by 20%, and then print the matrix with the increase, For example, this is the original matrix [200,300],[500,400] and I will increase 20% of each and show the matrix with new values [240,360],[600,480]

CodePudding user response:

You may wish to generate a new "matrix" with your adjusted values, in which case list comprehensions can be useful:

b = [[int(y * 1.2) for y in x] for x in a]

Printing the matrix we can find the widest number, then use str.rjust to ensure columns are lined up.

>>> w = len(str(max(max(x) for x in a)))
>>> str(400).rjust(w)
' 400'
>>> for x in a:
...   print(*(str(y).rjust(w) for y in x), sep=' ', end='\n')
... 
 200  300 5000  400
 554  500 1000  652
 800  500  650  800
 950  120  470  500
 500  600 2000  100
>>>

CodePudding user response:

This should work if you want to modify the original matrix; if not, Chris' answer is simpler.

for x in a:
    for i in range(len(x)):
        x[i] = int(x[i] * 1.2)
  • Related