所以这是我的文本文件,我想计算每年的平均值:
1969 324.000
1970 330.190
1970 326.720
1970 327.130
1971 326.970
1971 331.200
1971 329.430
1971 335.770
1971 337.600
这是我从另一个问题得到的代码,但它仍然存在错误:
In[2]: result = {}
with open('filename.txt', 'r') as f:
for line in f:
year, num = line.split()
year = int(year)
num = float(num)
try:
result[year].append(num)
except KeyError:
result[year] = [num]
In[3]: for k, v in sorted(result.items()):
print('Year: {}\tAverage: {:.2f}'.format(k, sum(v) / len(v)))
我的错误:预计缩进块
答案 0 :(得分:0)
好吧,看起来你不想在for循环后打算这条线。
with open('filename.txt', 'r') as f:
for line in f:
year, num = line.split()
...
答案 1 :(得分:0)
如果您有权访问pandas
,则该库会提供优化的解决方案。
import pandas as pd
from io import StringIO
mystr = StringIO("""1969 324.000
1970 330.190
1970 326.720
1970 327.130
1971 326.970
1971 331.200
1971 329.430
1971 335.770
1971 337.600""")
df = pd.read_csv(mystr, header=None, names=['Year', 'Amount'],
delim_whitespace=True)
res = df.groupby('Year')['Amount'].mean().to_dict()
结果:
{1969: 324.0, 1970: 328.01333333333338, 1971: 332.19400000000007}