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
相关产品推荐
相关产品推荐

