python multiply each item in sublists by a list

2019-08-04 03:55发布

问题:

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 sublist is multiplied by the first item in the multiplier list, the second item in each sublist is multiplied by the second item in the multiplier list, etc. The multiplier list is:

multiplier = [0.1, 0.3, 0.5, 0.8]

So that the ultimate result would be something like:

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] ]

How do I do this? I'm sorry if this question has been asked, I've been searching for hours and haven't found something that precisely applies.

回答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


回答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]]


回答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]


回答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]

def mult_lists(operator_list, operand_list):
    # Assuming both lists are same length
    result = []
    for n in range(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.



回答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))])

...