我想计算每年的平均值。这是我的文本文件:
#include <iostream>
#include <algorithm>
using namespace std;
void ToLower( std::string& ioValue )
{
std::transform( ioValue.begin(), ioValue.end(), ioValue.begin(), ::tolower );
}
std::string ToLower( const std::string& ioValue )
{
std::string aValue = ioValue;
ToLower(aValue);
return aValue;
}
int main()
{
string test = "test";
cout<<"Hello World" << endl;
// case 1
cout << ToLower("test") << endl;
// case 2
cout << ToLower(static_cast<string>(test)) << endl;
// case 3
cout << ToLower(string(test)) << endl;
如何在不导入图书馆的情况下计算每年的平均值? 我只知道如何计算平均值,例如1970年的线数与1971年相同。
这是我的代码,但到目前为止我只能计算整个文本文件的平均值:
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
答案 0 :(得分:0)
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)))
...:
Year: 1969 Average: 324.00
Year: 1970 Average: 328.01
Year: 1971 Average: 332.19