使用python在文本文件中打印平均值和每升成本



我试图得到成本值和每升成本的平均值。

r = []
with open('petrolPrice.txt') as f1:
r = f1.read()
s = r.split()
del s[0]
s.pop(0)

print(sum(s) / len(s)) # AVERAGE COST

with open('petrolPrice.txt') as f1:
r = f1.read()
s = r.split()
s.pop(0)

# COST PER LITER

这是下面的文本文件。使用标签空间划分升数和成本

Liters  Cost
20.0    56.40
9.6 29.95
5.0 15.60
15.0    54.30
18.4    65.32
18.7    75.36
17.7    80.00

在文本文件中打印平均值和每升成本。

import pandas as pd
with open("input.txt") as f:
lines = f.readlines()
#get first value of every line as Liters 
liters = [(line.split()[0]) for line in lines if line.split()[0] != 'Liters']
#get second value of every line as Cost
cost = [(line.split()[1]) for line in lines if line.split()[1] != 'Cost']
#df with Liters and Cost
df = pd.DataFrame({'Liters': liters, 'Cost': cost})
#add column with cost per liter
df['Cost per liter'] = df['Cost'].astype(float) / df['Liters'].astype(float)
#add row with mean
df.loc[len(liters)] = [df['Liters'].astype(float).mean(), df['Cost'].astype(float).mean(), df['Cost per liter'].astype(float).mean()]
#df to text
df.to_csv('output.txt', sep='t', index=False)

打开文件,一次读取一行。跳过第一行。将两个(预期(以空格分隔的标记转换为float。求和这些值。做最后的计算。

totalLitres = 0
totalCost = 0
with open('petrolPrice.txt') as pp:
next(pp) # skip heading
for line in pp:
litres, cost = map(float, line.split())
totalLitres += litres
totalCost += cost
print(f'Average cost per litre = {totalCost/totalLitres:.2f}')

输出:

Average cost per litre = 3.61

最新更新