我正在编写一个简单的程序,在导入一个文本文件后输出一个基本图形。我得到以下错误:
Traceback (most recent call last):
File "C:\Users\Chris1\Desktop\attempt2\ex1.py", line 13, in <module>
x.append(int(xAndY[0]))
ValueError: invalid literal for int() with base 10: '270.286'
我的python代码如下所示:
^{pr2}$我的文本文件片段如下所示:
270.286,4.353,16968.982,1903.115
38.934,68.608,16909.727,1930.394
190.989,1.148,16785.367,1969.925
这个问题看起来很小,但似乎自己解决不了 谢谢
解决方案
如果要将浮点值转换为整数,只需更改
到
^{pr2}$你出错的原因
出现错误是因为内置函数
int
不接受浮点的字符串表示作为其参数。从documentation:在您的例子中(x不是数字,而是浮点的字符串表示),这意味着函数不知道如何转换值。这是因为使用
base=10
,参数只能包含数字[0-9],即不能包含.
(点),这意味着字符串不能是浮点的表示。在更好的解决方案
我建议您研究一下^{} ,因为这样更容易使用:
在更正后,它将生成与代码中相同的
x
和y
列表。在通过这个修改,您的代码可以被缩减为
很简单,只需将
int
转换替换为float
:这将修复错误。在
相关问题 更多 >
编程相关推荐