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

Python函数问题:两等长列表对应元素相乘仅返回首个乘积

问题原因

你的函数只返回[1]是因为**return语句放在了for循环内部**——函数执行到return就会立刻终止,第一次循环(i=0)时就直接返回了第一个元素的乘积列表,后面的循环根本没机会运行。

修正方案

方法一:初始化空列表,遍历填充后返回

a = [1, 2, 3]
b = [1, 4, 5]

def list_mult(a, b):
    if len(a) != len(b):
        # 这里返回错误信息更严谨,避免后续代码继续执行出错
        return "error, lists must be the same size"
    result = []
    for i in range(len(a)):
        result.append(a[i] * b[i])
    return result

print(list_mult(a, b))  # 输出 [1, 8, 15]

方法二:用列表推导式简化代码

a = [1, 2, 3]
b = [1, 4, 5]

def list_mult(a, b):
    if len(a) != len(b):
        return "error, lists must be the same size"
    return [x * y for x, y in zip(a, b)]

print(list_mult(a, b))  # 输出 [1, 8, 15]

额外优化建议

原代码中列表长度不等时仅打印错误,但函数仍会继续执行循环,容易引发异常。可以改成抛出异常更规范:

if len(a) != len(b):
    raise ValueError("lists must be the same size")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:01:13