2

如何使用函数在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

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

所以输出将是 1、4、9 和 16。我将如何在第二个列表可以是任何东西的 python 中执行此操作?谢谢

4

6 回答 6

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但到那时,对'd 列表使用列表推导可能更有意义。

[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 generator that generate) [(a,x),(b,y),(c,z)]

for a, b in每一对“解包”(m,n)到变量ab中,并将a*b它们相乘。

于 2013-09-26T00:25:07.237 回答
4

您可以使用列表推导:

>>> 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]
于 2013-09-26T00:22:25.780 回答
0

如果您有两个相同长度的列表,最简单的方法A是:Bzip

>>> 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)]
于 2013-09-26T00:25:36.717 回答
0

zip()会做:

[a*b for a,b in zip(lista,listb)]
于 2013-09-26T00:42:06.933 回答
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,如此处所建议的

于 2017-06-17T04:48:53.283 回答
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])
于 2020-05-19T21:06:20.590 回答