如何使用函数将列表相乘?

时间:2013-09-26 00:21:32

标签: python list multiplying

如何使用函数在python中将列表相乘?这就是我所拥有的:

    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

所以我想用它来乘以列表*列表(1 * 1,2 * 2,3 * 3,4 * 4)

所以输出将是1,4,9和16.我如何在python中执行此操作,其中第二个列表可以是什么? 感谢

6 个答案:

答案 0 :(得分:9)

我最喜欢的方法是将mul运算符映射到两个列表:

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,至少在Python 3中,返回一个生成器。因此,如果您想要一个列表,您应该将其转换为一个:

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

但到那时,对zip'列表使用列表理解可能更有意义。

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

要解释最后一个,zip([a,b,c], [x,y,z])给出(生成的生成器)[(a,x),(b,y),(c,z)]

for a, b in“将每个(m,n)对解包为变量aba*b将它们相乘。

答案 1 :(得分:3)

您可以使用列表理解:

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

请注意,1*1, 2*2, etc与平方数字相同。


如果您需要将两个列表相乘,请考虑zip()

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

答案 2 :(得分:0)

如果您有两个相同长度的AB列表,最简单的就是zip他们:

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

单独查看zip以了解其工作原理:

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

答案 3 :(得分:0)

zip()可以:

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

答案 4 :(得分:0)

如其他答案所示,

zip可能是要走的路。也就是说,这是一种替代的初学者方法。

# 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))

都给出了:

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

另一种方法是使用numpy,as suggested here

答案 5 :(得分:0)

为此使用numpy。

>>> import numpy as np
>>> list = [1,2,3,4]
>>> np.multiply(list, list)
array([ 1,  4,  9, 16])

如果您喜欢python列表:

>>> np.multiply(list, list).tolist()
[1, 4, 9, 16]

此外,这也适用于带有标量的按元素乘法。

>>> np.multiply(list, 2)
array([2, 4, 6, 8])