用理解替换Python嵌套For循环[复制]

问题描述 投票:1回答:2

这个问题在这里已有答案:

我正在寻找一种方法来使用列表推导来实现以下目的:

a = [1,2,3,4]
b = [5,6,7,8]
vals = []

for i in a:
  for j in b:
    vals.append(i*j)

print(vals)

我确信有一种方法可以用列表理解来做到这一点,但我对如何继续进行感到茫然。

python for-loop list-comprehension
2个回答
4
投票

纯列表理解:

[i*j for i in a for j in b]

输出:

[5, 6, 7, 8, 10, 12, 14, 16, 15, 18, 21, 24, 20, 24, 28, 32]

1
投票

itertools的product将为您提供两个列表中所有元素的组合。然后,您可以使用理解来乘以每对:

from itertools import product
print([x[0] * x[1] for x in product(a, b)])
© www.soinside.com 2019 - 2024. All rights reserved.