Warm tip: This article is reproduced from stackoverflow.com, please click
for-loop list matrix python

Multiply list of lists with elements of multiplier list Python

发布于 2020-04-11 22:27:52

I want to multiply the lists below with the elements of a multiplier list. So that multiplier[0] multiplies the first list in list of lists, multiplier[1] multiplies the second list in list of lists etc.

Thank you!

I have tried this so far:

[a*b for a,b in zip(multiplier,list_of_lists)]

This is the list of lists:

[[0, 0, 1, 1], 
[1, 0, 0, 0], 
[1, 1, 1, 1], 
[1, 2, 0, 1]]

Multiplier list:

[1.0, 2.0, 0.0, 0.41503749927884376]
Questioner
rex9311
Viewed
56
Olvin Roght 2020-02-02 21:07

If you'll convert your code from list comprehension into simple loop, you will see where problem is:

result = []
for a, b in zip(multiplier, list_of_lists):
    result.append(a * b)  # appends a copies of list b

It's definitely not what you're trying to do. You need nested loop to iterate over items of inner lists:

result = []
for multiplier, sub_list in zip(multipliers, list_of_lists):
    new_list = []
    for item in sub_list:
        new_list.append(multiplier * item)
    result.append(new_list)

Or you can write it shorter using nested list comprehension (you can give variables shorter names to look more "compact"):

result = [[multiplier * item for item in sub_list] for multiplier, sub_list in zip(multipliers, list_of_lists)]