Python Multiply Each Item In Sublists By A List
I have a list of sublists, such as this: t = [ [1, 2, 3, 4], [2, 5, 7, 9], [7, 9, 11, 4] ] I want to multiply each of the sublists by a list such that the first item in each sublis
Solution 1:
Actually, numpy makes it easier:
import numpy as np
t = np.array([ [1, 2, 3, 4], [2, 5, 7, 9], [7, 9, 11, 4] ])
multiplier = np.array([0.1, 0.3, 0.5, 0.8])
answer = t * multiplier
Solution 2:
total_result = list()
for v in t:
result = list()
for num, mul in zip(v, multiplier):
result.append(round(num*mul, 2))
total_result.append(result)
or just one line
total_result = [[round(num*mul, 2) for num, mul in zip(v, multiplier)] for v in t]
total_result
[[0.1, 0.6, 1.5, 3.2], [0.2, 1.5, 3.5, 7.2], [0.7, 2.7, 5.5, 3.2]]
Solution 3:
numpy
(Numpy)would handle all this:
import numpy as np
t = np.array([ [1, 2, 3, 4], [2, 5, 7, 9], [7, 9, 11, 4] ])
multiplier = np.array([0.1, 0.3, 0.5, 0.8])
new_t = [e*multiplier for e in t]
Solution 4:
Numpy would probably be the easiest solution, but if you wanted to do without:
t = [[1, 2, 3, 4], [2, 5, 7, 9], [7, 9, 11, 4]]
multiplier = [0.1, 0.3, 0.5, 0.8]
defmult_lists(operator_list, operand_list):
# Assuming both lists are same length
result = []
for n inrange(len(operator_list)):
result.append(operator_list[n]*operand_list[n])
return result
multiplied_t = list(map(lambda i: mult_lists(multiplier, i), t)))
map
calls the mult_lists
function for each item in t
, then it is arranged in a list.
Solution 5:
You can use list comprehension:
[[li[i]*multiplier[i] for i in range(len(multiplier))] for li in t]
For clarity, expanded iterative version is:
new_list = []
for li in t:
new_list.append([li[i]*multiplier[i] for i in range(len(multiplier))])
...
Post a Comment for "Python Multiply Each Item In Sublists By A List"