执行两个列表列表的数学计算

时间:2017-04-23 03:24:54

标签: python list

我有两个列表列表:

L1 = [[2.1,2.2],[2.3,2.4],[2.5,2.6]]
L2 = [[3.1,3.2],[3.3,3.4],[3.5,3.6]]

我想写一个python程序从L1中提取每个列表以与L2进行比较并执行类似乘法的操作?

示例:python从L1获取[2.1,2.2]并与[3.1,3.2]进行比较并执行乘法的情况。

我已经尝试了,但似乎我做得不对。注意: multiplicationL 是定义的函数,将两个列表作为参数

L1 = [[2.1,2.2],[2.3,2.4],[2.5,2.6]]
L2 = [[3.1,3.2],[3.3,3.4],[3.5,3.6]]

for i in L1:
    for j in L2:
         result = multiplicationL(L1[i],L2[j])
print(result)

坦率地说,我想从L1获取一个列表,从L2获取一个列表并对它们执行操作。

2 个答案:

答案 0 :(得分:0)

对于乘法,这将完成工作:

L1 = [[2.1,2.2],[2.3,2.4],[2.5,2.6]]
L2 = [[3.1,3.2],[3.3,3.4],[3.5,3.6]]

result=[]
for i in L1:
    for j in L2:
         res = [i[a]*j[a] for a in range(len(i))]
         result.append(res)
print(result)

为了将其推广到其他操作,您可以在单独的函数中定义操作,如下所示:

L1 = [[2.1,2.2],[2.3,2.4],[2.5,2.6]]
L2 = [[3.1,3.2],[3.3,3.4],[3.5,3.6]]

def multiply(i,j):
    return [i[a]*j[a] for a in range(len(i))]

result=[]
for i in L1:
    for j in L2:
         res = multiply(i,j)
         result.append(res)
print(result)

打印

[[6.510000000000001, 7.040000000000001], [6.93, 7.48], [7.3500000000000005, 7.920000000000001], [7.13, 7.68], [7.589999999999999, 8.16], [8.049999999999999, 8.64], [7.75, 8.32], [8.25, 8.84], [8.75, 9.360000000000001]]

答案 1 :(得分:0)

import numpy as np

L1 = [[2.1,2.2],[2.3,2.4],[2.5,2.6]]
L2 = [[3.1,3.2],[3.3,3.4],[3.5,3.6]]

for i in L1:
    for j in L2:
        print(np.dot(i,j))
   ...:         

13.55
14.41
15.27
14.81
15.75
16.69
16.07
17.09
18.11