[英]TypeError: a float is required,Python
I want to convert list of floats into integers. 我想将浮点数列表转换为整数。 My code 我的密码
import math
data1 = [line.strip() for line in open("/home/milenko/Distr70_linux/Projects/Tutorial_Ex3/myex/base.txt", 'r')]
print type(data1)
data1c = [int(math.floor(i)) for i in data1]
print data1c[0]
What should I change? 我应该改变什么? File is huge,just couple of lines 文件很大,只有几行
1.200000e+03
1.200000e+03
1.200000e+03
1.200000e+03
1.200000e+03
1.200000e+03
1.200000e+03
1.200000e+03
You need to first cast to float: 您需要先强制浮动:
[int(float(i)) for i in data1]
calling int
will floor the number for you: 调用int
将为您设置电话号码:
In [8]: int(float("1.23456e+03"))
Out[8]: 1234
You can do it all in the file logic: 您可以在文件逻辑中完成所有操作:
with open("/home/milenko/Distr70_linux/Projects/Tutorial_Ex3/myex/base.txt", 'r') as f:
floored = [int(float(line)) for line in f]
It is good practice to use with to open your files, it will handle the closing of your files for you. 最好使用与一起打开文件,它将为您处理文件的关闭。 Also int and float can handle leading or trailing white space so you don't need to worry about using strip. 另外, int和float可以处理前导或尾随空白,因此您无需担心使用strip。
Also if you were just wanting to pull the floats and not also floor, map
is a nice way of creating a list of floats, ints etc.. from a file or any iterable: 另外,如果您只是想拉浮子而不是地板,则map
是从文件或任何可迭代的对象创建浮子,整数等的列表的好方法。
floored = list(map(float, f))
Or using python3 where map returns an iterator, you could double map: 或者使用python3,其中map返回迭代器,您可以将map加倍:
floored = list(map(int, map(float, f)))
The equivalent code in python2 would be using itertools.imap
python2中的等效代码将使用itertools.imap
from itertools import imap
floored = map(int, imap(float, f))
Data read from files are always of str
type where as parameter required for math.floor
is a float 从文件中读取的数据始终为str
类型,其中math.floor
是float类型的参数
So you need convert it into float 所以你需要将其转换为浮点数
data1c = [int(float(i)) for i in data1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.