python - 将列表从字符串转换为 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))
并且是否可以从文件中获得与数字相同的输出格式。
我尝试将其转换为浮点数,但所有坐标都得到小数位。
解决方案
您可以使用此代码适当地转换输入,使用这种 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'>
我不知道您的输入如何存储在您正在阅读的文件/另一个列表中,但您知道如何解析单个输入。
推荐阅读
- c# - C#如何从网站只获取一个字符串
- jenkins - 从管道脚本将环境变量设置为 Allure 报告
- python - 如何使用 gensim 在 Windows 上运行 word2vec
- python - 在现场运行 Python 程序
- sass - Sass根据body类改变变量的值?
- logging - 如何在 elixir 中为除控制台以外的后端记录器启用记录器白名单?
- java - Jdbc:在应用程序退出时运行语句会发生什么?
- angular - 更新角度共享组件中的视图(html)
- mysql - 最后一个点之后的子字符串
- python - AttributeError:模块“sklearn”没有属性“model_selection”