简体   繁体   中英

Without using panda or numpy, how would I separate my data into even columns? Then sum up the last column

I am trying to align the year, model, and price. Then sum up the cost.

Saved as 'car.dat' data below without converting to csv or using panda and numpy.

2018,Alfa Romeo Stelvio Ti,$28,950

2022,Mercedes-Benz E350,$54,950

2022,Volvo XC90,49,900

What I have so far using 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()

Expected results below:

在此处输入图像描述

Perhaps something similar to this:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM