如果不使用 panda 或 numpy,我如何将我的数据分成偶数列?然后总结最后一列
Without using panda or numpy, how would I separate my data into even columns? Then sum up the last column
我正在尝试调整年份、型号和价格。然后总结成本。
保存为 'car.dat' 以下数据,未转换为 csv 或使用 panda 和 numpy。
2018,Alfa Romeo Stelvio Ti,,950
2022,Mercedes-Benz E350,,950
2022,Volvo XC90,49,900
到目前为止我使用 python idle shell 3.10.4:
def main():
file = open('car.dat','r')
content = file.readlines()
#total =0
#total = all 3 rows.
for line in content:
print ('Year' 'Make/Model', 'Price')
print ('-'*35)
line = line.split('\n')
print(line[0].replace(',',' ',2))
#print ('Total'+ total)
main()
预期结果如下:
可能类似于此:
def main():
total = 0
print("Year".ljust(6), "Make/Model".ljust(10), "Price")
print("-" * 35)
with open('car.dat') as f:
for line in f:
year, make_model, price = line.split(",")
print(year.ljust(6), make_model.ljust(10), price)
total += int(price)
print("-" * 35)
print("total".rjust(16), str(total))
if __name__ == "__main__":
main()
我正在尝试调整年份、型号和价格。然后总结成本。
保存为 'car.dat' 以下数据,未转换为 csv 或使用 panda 和 numpy。
2018,Alfa Romeo Stelvio Ti,,950
2022,Mercedes-Benz E350,,950
2022,Volvo XC90,49,900
到目前为止我使用 python idle shell 3.10.4:
def main():
file = open('car.dat','r')
content = file.readlines()
#total =0
#total = all 3 rows.
for line in content:
print ('Year' 'Make/Model', 'Price')
print ('-'*35)
line = line.split('\n')
print(line[0].replace(',',' ',2))
#print ('Total'+ total)
main()
预期结果如下:
可能类似于此:
def main():
total = 0
print("Year".ljust(6), "Make/Model".ljust(10), "Price")
print("-" * 35)
with open('car.dat') as f:
for line in f:
year, make_model, price = line.split(",")
print(year.ljust(6), make_model.ljust(10), price)
total += int(price)
print("-" * 35)
print("total".rjust(16), str(total))
if __name__ == "__main__":
main()