我有下面的Python代码:
carFile = open("cars.txt", "r")
file_data = carFile.read()
carFile.close()
car_details_name = file_data.split("\n")[0].split("-")
car_details = file_data.split("\n")[1:]
cars = []
no_of_cars = len(car_details)
for i in range(no_of_cars):
car = dict()
for j, detail in enumerate(car_details_name):
car[detail] = car_details[i].split("-")[j]
car["car_price"] = str(int(car["selling_price"]) - int(car["discount"]) + int(car["tax"]))
car["car_type"] = "LUXURY" if int(car["car_price"])>=8000 else "CONVENIENCE"
cars.append(car)
car_details_name.append('car_price')
car_details_name.append('car_type')
for i in range(no_of_cars):
print(cars[i])
print("\n")
processedCarFile = open("processedcars.txt", "w")
luxuryCarFile = open("luxurycars.txt", "w")
convenienceCarFile = open("conveniencecars.txt", "w")
processedCarFile.write(" - ".join(car_details_name) + "\n")
luxuryCarFile.write(" - ".join(car_details_name) + "\n")
convenienceCarFile.write(" - ".join(car_details_name) + "\n")
for car in cars:
processedCarFile.write(" - ".join(list(car.values())) + "\n")
if car["car_type"]=="LUXURY":
luxuryCarFile.write(" - ".join(list(car.values())) + "\n")
else:
convenienceCarFile.write(" - ".join(list(car.values())) + "\n")
processedCarFile.close()
luxuryCarFile.close()
convenienceCarFile.close()
这是cars.txt的内容
car_model_number-car_manufacturer-tax-selling_price-discount
15AB83FUFBFU8-Maruti Suzuki-1000-7000-500
54GDG8FHNJVFV-Tata-800-7200-800
FRF84R99NKFNF-Mahindra-1000-8000-1200
HFD748BF4FJBF-Hyundai-750-11000-1750
我得到以下错误:
IndexError Traceback (most recent call last)
Cell In[1], line 17
15 car = dict()
16 for j, detail in enumerate(car_details_name):
---> 17 car[detail] = car_details[i].split("-")[j]
19 car["car_price"] = str(int(car["selling_price"]) - int(car["discount"]) + int(car["tax"]))
21 car["car_type"] = "LUXURY" if int(car["car_price"])>=8000 else "CONVENIENCE"
IndexError: list index out of range
有人能帮我修一下吗?
1条答案
按热度按时间vdzxcuhz1#
这演示了如何通过使用适当的标准模块来轻松地处理问题中显示的数据。
由于OP在这方面的意图不清楚,因此此处未显示3个输出文件的处理。
输出: