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

Python列表中字符串、浮点型转整数未生效问题求助

问题原因分析
  • int(i) 是纯函数调用,只会返回转换后的整数对象,不会修改原列表中的元素值,也不会修改遍历过程中的临时变量i对应的原列表位置内容
  • 你当前的遍历逻辑没有把转换结果回写到列表,也没有生成新的存储转换结果的容器,所以原列表全程没有发生变化,后续求和时遇到字符串类型的数字就会抛出类型错误
修复方案

你可以直接生成新的存储转换后整数的列表返回即可,修改后的代码如下:

class NumbersIterable:
    def __init__(self, numbers):
        self.numbers = numbers
        print(self.numbers)
    
    def runConversion(self):
        return NumbersIterator.convertNumbers(self.numbers)

class NumbersIterator:
    @staticmethod
    def convertNumbers(numbers):
        print('in numbers')
        # 生成新列表存储转换后的整数
        converted = []
        for i in numbers:
            converted.append(int(i))
        print(converted)
        return converted

niterable = NumbersIterable(["1", 2.0, "4",5,6.1,"7",8,9.2])
niterable = niterable.runConversion()

sum_total = 0
for i in niterable:
    print(i)
    sum_total += i
print("sum =", sum_total)

注意:上述代码中我们给convertNumbers加了@staticmethod装饰器符合类静态方法的规范,同时避免了和内置函数sum重名,将求和变量改为了sum_total。如果需要兼容字符串格式的浮点数(比如"3.14"),可以把转换逻辑改为int(float(i))即可,转换时会自动截断小数部分。

运行后的输出结果总和为42,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:24:04