How do I multiply lists together using a function?

狂风中的少年 提交于 2019-12-20 03:02:08

问题


how do I multiply lists together in python using a function? This is what I have:

    list = [1, 2, 3, 4]
    def list_multiplication(list, value):
         mylist = []
         for item in list:
              for place in value:
               mylist.append(item*value)
    return mylist

So I want to use this to multiply list*list (1*1, 2*2, 3*3, 4*4)

So the output would be 1, 4, 9, and 16. How would I do this in python where the 2nd list could be anything? Thanks


回答1:


My favorite way is mapping the mul operator over the two lists:

from operator import mul

mul(2, 5)
#>>> 10

mul(3, 6)
#>>> 18

map(mul, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10])
#>>> <map object at 0x7fc424916f50>

map, at least in Python 3, returns a generator. Hence if you want a list you should cast it to one:

list(map(mul, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10]))
#>>> [6, 14, 24, 36, 50]

But by then it might make more sense to use a list comprehension over the zip'd lists.

[a*b for a, b in zip([1, 2, 3, 4, 5], [6, 7, 8, 9, 10])]
#>>> [6, 14, 24, 36, 50]

To explain the last one, zip([a,b,c], [x,y,z]) gives (a generator that generates) [(a,x),(b,y),(c,z)].

The for a, b in "unpacks" each (m,n) pair into the variables a and b, and a*b multiplies them.




回答2:


You can use a list comprehension:

>>> t = [1, 2, 3, 4]
>>> [i**2 for i in t]
[1, 4, 9, 16]

Note that 1*1, 2*2, etc is the same as squaring the number.


If you need to multiply two lists, consider zip():

>>> L1 = [1, 2, 3, 4]
>>> L2 = [1, 2, 3, 4]
>>> [i*j for i, j in zip(L1, L2)]
[1, 4, 9, 16]



回答3:


If you have two lists A and B of the same length, easiest is to zip them:

>>> A = [1, 2, 3, 4]
>>> B = [5, 6, 7, 8]
>>> [a*b for a, b in zip(A, B)]
[5, 12, 21, 32]

Take a look at zip on its own to understand how that works:

>>> zip(A, B)
[(1, 5), (2, 6), (3, 7), (4, 8)]



回答4:


zip() would do:

[a*b for a,b in zip(lista,listb)]



回答5:


zip is probably the way to go, as suggested by the other answers. That said, here's an alternative beginner approach.

# create data
size = 20
a = [i+1 for i in range(size)]
b = [val*2 for val in a]

a
>> [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20] 
b
>> [ 2  4  6  8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40] 

def multiply_list_elems(list_one, list_two):
    """ non-efficient method """
    res = [] # initialize empty list to append results
    if len(a) == len(b): # check that both lists have same number of elems (and idxs)
        print("\n list one: \n", list_one, "\n list two: \n", list_two, "\n")
        for idx in range(len(a)): # for each chronological element of a
            res.append(a[idx] * b[idx]) # multiply the ith a and ith b for all i
    return res

def efficient_multiplier(list_one, list_two):
    """ efficient method """
    return [a[idx] * b[idx] for idx in range(len(a)) if len(a) == len(b)]

print(multiply_list_elems(a, b))
print(efficient_multiplier(a, b))

both give:

>> [2, 8, 18, 32, 50, 72, 98, 128, 162, 200, 242, 288, 338, 392, 450, 512, 578, 648, 722, 800]

Yet another approach is using numpy, as suggested here.



来源:https://stackoverflow.com/questions/19017301/how-do-i-multiply-lists-together-using-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!