如何将两个嵌套列表的每个元素相乘?

时间:2018-07-19 14:32:36

标签: python

有2个嵌套列表,我想在相应位置上乘以项目,因此输出为[[9, 16, 21], [24, 25, 24], [21, 16, 9]]。 我使用下面的程序。它可以工作,但是看起来太复杂了。有什么快速的方法吗?有没有可以快速执行此类任务的库?

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
n = []
for i in range(3):
    m = []
    for j in range(3):
        m.append(a[i][j] * b[i][j])
    n.append(m)
print(n)

2 个答案:

答案 0 :(得分:4)

您可以两次申请java.util.concurrent.ExecutionException: java.lang.IllegalStateException: No Client ALPNProcessors! at org.eclipse.jetty.util.FuturePromise.get(FuturePromise.java:138) at com.blazemeter.jmeter.http2.sampler.HTTP2Connection.connect(HTTP2Connection.java:65) at com.blazemeter.jmeter.http2.sampler.HTTP2Request.setConnection(HTTP2Request.java:247) at com.blazemeter.jmeter.http2.sampler.HTTP2Request.sample(HTTP2Request.java:121) at com.blazemeter.jmeter.http2.sampler.HTTP2Request.sample(HTTP2Request.java:107) at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:490) at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:416) at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:250) at java.base/java.lang.Thread.run(Unknown Source) Caused by: java.lang.IllegalStateException: No Client ALPNProcessors! at org.eclipse.jetty.alpn.client.ALPNClientConnectionFactory.<init>(ALPNClientConnectionFactory.java:57) at org.eclipse.jetty.http2.client.HTTP2Client.lambda$doStart$1(HTTP2Client.java:155) at org.eclipse.jetty.http2.client.HTTP2Client$ClientSelectorManager.newConnection(HTTP2Client.java:438) at org.eclipse.jetty.io.ManagedSelector.createEndPoint(ManagedSelector.java:222) at org.eclipse.jetty.io.ManagedSelector.access$1500(ManagedSelector.java:60) at org.eclipse.jetty.io.ManagedSelector$CreateEndPoint.run(ManagedSelector.java:825) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:754) at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:672) ... 1 more Suppressed: java.lang.IllegalStateException: org.eclipse.jetty.alpn.java.client.OpenJDK8ClientALPNProcessor@e23ec5a not applicable for java 10.0.2 at org.eclipse.jetty.alpn.java.client.OpenJDK8ClientALPNProcessor.init(OpenJDK8ClientALPNProcessor.java:41) at org.eclipse.jetty.alpn.client.ALPNClientConnectionFactory.<init>(ALPNClientConnectionFactory.java:77) ... 8 more

zip

输出:

a=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b=[[9, 8, 7], [6, 5, 4], [3, 2, 1]]
result = [[j*k for j, k in zip(c, d)] for c, d in zip(a, b)]

答案 1 :(得分:1)

您可以map列出乘法运算符:

from functools import partial
from operator import mul
print(list(map(list, map(partial(map, mul), a, b))))

输出:

[[9, 16, 21], [24, 25, 24], [21, 16, 9]]

如果您使用的是Python 2.x,则也可以跳过到列表的转换:

print map(partial(map, mul), a, b)