You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现两个列表中的元素两两相乘并生成结果列表

实现方案

方法1:列表推导式(最简洁高效)

这是Python中适配该需求的最优写法,嵌套遍历两个列表完成乘积运算即可:

list1 = [1,2,3]
list2 = [4,5,6]
list3 = [a * b for a in list1 for b in list2]

运行后直接得到目标结果 [4, 5, 6, 8, 10, 12, 12, 15, 18]。

方法2:嵌套for循环(适合新手理解逻辑)

如果对列表推导式不熟悉,可以用显式嵌套循环实现,逻辑和列表推导式完全一致:

list1 = [1,2,3]
list2 = [4,5,6]
list3 = []
for a in list1:
    for b in list2:
        list3.append(a * b)

方法3:itertools.product实现(适合多列表扩展场景)

如果后续需要扩展到3个及以上列表的元素组合运算,可以用标准库itertools.product生成笛卡尔积再做运算:

from itertools import product

list1 = [1,2,3]
list2 = [4,5,6]
list3 = [a * b for a, b in product(list1, list2)]

内容的提问来源于stack exchange,提问作者Edward Serfontein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:36:04