我有一个输入2个txt文件的程序。
deaths.txt
29.0
122.0
453.0
years.txt
1995
1996
1997
我根据数据制作清单
deaths = open("deaths.txt").read().splitlines()
years = open("years.txt").read().splitlines()
然后我将列表转换为int和float
for x in years[:-1]:
x = int(x)
for x in deaths[:-1]:
x = float(x)
然后是错误的部分:ValueError: could not convert string to float
plt.plot(years, deaths)
所以它说不能将字符串转换为浮点数。但我以为我已经做到了。可能是什么原因?
答案 0 :(得分:3)
以下内容应该让你前进。而不是使用readlines()
来读取整个文件,更好的方法是在读入时转换每一行。
由于您的两个数据文件具有不同数量的元素,因此代码会使用zip_longest
使用0.0
填充任何缺失的死亡数据:
from itertools import zip_longest
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
with open('deaths.txt') as f_deaths:
deaths = [float(row) for row in f_deaths]
with open('years.txt') as f_years:
years = [int(row) for row in f_years]
# Add these to deal with missing data in your files, (see Q before edit)
years_deaths = list(zip_longest(years, deaths, fillvalue=0.0))
years = [y for y, d in years_deaths]
deaths = [d for y, d in years_deaths]
print(deaths)
print(years)
plt.xlabel('Year')
plt.ylabel('Deaths')
ax = plt.gca()
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%d'))
ax.set_xticks(years)
plt.plot(years, deaths)
plt.show()
这将在屏幕上显示以下内容,显示对int和浮点数的转换是正确的:
[29.0, 122.0, 453.0, 0.0]
[1995, 1996, 1997, 1998]
然后会显示以下图表: