Reputation: 21
I created a function which updates the single list by adding the interest rate.
def first(lst, rate):
for i in range(len(lst)):
lst[i] += lst[i] * rate[i]
My question is, how to use this function to update two dimensional list by adding the interest rate?
For example:
lst2 = [[25, 10, 300], [7, 30, 80], [7, 530, 24],[65, 30, 2]]
rate = [0.5, 0.02, 0.15]
>>> for i in lst2:
print(i)
[37.5, 10.2, 345.0]
[10.5, 30.6, 92.0]
[10.5, 540.6, 27.6]
[97.5, 30.6, 2.3]
My code:
def second(lst2, rate):
for x in lst2:
for y in x:
lst2[x][y] += first(lst2[x][y],rate[x])
Any help will be much appreciated. Thanks
Upvotes: 0
Views: 69
Reputation: 5786
Easy way is to say
for i in range(len(lst2)):
first(lst2[i], rate)
lst2 will then contain [[37.5, 10.2, 345.0], [10.5, 30.6, 92.0], [10.5, 540.6, 27.6], [97.5, 30.6, 2.3]]
Upvotes: 0
Reputation: 17505
This situation is kind of strange, because you're completely relying on the functions having side-effects instead of returning values. However, here's a solution:
def second(lst2, rate):
for i in range(len(lst2)):
first(lst2[i], rate)
Upvotes: 1
Reputation: 3229
Short answer: this is what numpy is for.
import numpy
lst2 = numpy.array( [ ..as above.. ])
rate = numpy.array( [.. as above.. ])
lst_with_interest = lst2 + lst2*rate[numpy.newaxis,:]
Without numpy, it's possible lots of different ways, mostly depending on how general you want the solution to be. A good general way is to write something which does a single dimension, and looks at its parameters to see if the rate is a list or a single number; see the zip() function for dealing with the list case.
Upvotes: 0