我有一个data.txt:
1.30000E+01 7.49106E+01
1.40000E+01 7.24673E+01
...
我想将第一列乘以2.这是我的代码:
with open("data.txt") as f:
data = f.readlines()
xtemp = [row.split()[0] for row in data]
y = [row.split()[1] for row in data]
x = [i * 2 for i in xtemp]
错误信息是
eError: invalid literal for float():1.30000E+011.30000E+01
答案 0 :(得分:3)
从文件读取的数据是string类型。你需要转换为float to multiply:
x = [float(i) * 2 for i in xtemp]
import io
filedata = """1.30000E+01 7.49106E+01
1.40000E+01 7.24673E+01"""
data = [i.strip("\n") for i in io.StringIO(filedata).readlines()]
xtemp = [row.split()[0] for row in data]
y = [row.split()[1] for row in data]
xtype = [type(i) for i in xtemp] # [str,str] <-- here is your problem
x = [float(i) * 2 for i in xtemp]
x
返回
[26.0, 28.0]