首页 > 解决方案 > 将列表从字符串转换为 int 但有一个问题

问题描述

我首先要说我对编程知之甚少,我尝试搜索答案,但我什至不知道在搜索引擎中输入什么内容。所以这里。

class Point:
    def __init__ (self, x, y):
        self.x = x
        self.y = y
    
    def __str__ (self):
        return "Members are: %s, %s" % (self.x, self.y)

我有这个类,它表示一个带有 x 和 y 坐标的点。

我有一个列表points = [],如果我手动将一个点附加到该列表,例如points.append(Point(-1.0, 3))输出返回(-1.0, 3),我正在对这些点进行一些计算,但我认为将代码放在这里并不重要。

事情变得棘手,因为我必须从文件中输入数字。我已经将它们添加到另一个列表并使用循环附加它们。问题是列表在str中,如果我将它转换为int,我会因为小数而出现错误.0它在我的作业中说我必须保持与输入相同的格式。

我不明白的是,.0当我像这样输入它时它如何保持小数点,points.append(Point(-1.0, 3))并且是否可以从文件中获得与数字相同的输出格式。

我尝试将其转换为浮点数,但所有坐标都得到小数位。

标签: pythonlistclass

解决方案


您可以使用此代码适当地转换输入,使用这种 try-catch 机制,我们首先尝试int,然后如果我们没有成功,我们继续使用float

def float_or_int(inp):
    try:
        n = int(inp)
    except ValueError:
        try:
            n = float(inp)
        except ValueError:
            print("it's not int or float")
    return n


input_1 = '10.3'
input_2 = '10.0'
input_3 = '10'

res1 = float_or_int(input_1)  
res2 = float_or_int(input_2)  
res3 = float_or_int(input_3)  

print(res1, type(res1))  # 10.3 <class 'float'>
print(res2, type(res2))  # 10.0 <class 'float'>
print(res3, type(res3))  # 10 <class 'int'>

我不知道您的输入如何存储在您正在阅读的文件/另一个列表中,但您知道如何解析单个输入。


推荐阅读