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

Python遍历分割列表问题:代码仅返回最后元素平方求解决

问题解决:让列表中每个数字都被平方

你的问题出在循环内部重复初始化空列表:每次执行for num in list.split()时,你都重新创建了一个空的squares列表,之前循环添加的元素全被清空,最后自然只剩最后一个数字的平方。

修正方法很简单,把squares = []移到for循环的外面,让列表只初始化一次:

def squareEach(input_str):
    squares = []  # 将列表初始化移到循环外部
    for num in input_str.split():
        square = int(num) * int(num)
        squares.append(square)
    return squares

def main():
    nums = input("Please enter a list of numbers: ")
    print("The squares of the numbers are:", squareEach(nums))

另外提醒:不要用list作为参数名,它是Python内置的类型名称,容易引发命名混淆,这里改成input_str更清晰。

测试输入1 2 3 6,现在会输出:The squares of the numbers are: [1, 4, 9, 36]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 09:57:00