如何通过遍历列表索引获取从文件读取的客户数据中的名称及对应详情并实现查询计算
Fixing Your Customer Data Reader and Adding Query Functionality
Let's break this down step by step to fix your code and build the query feature you need.
Issues in the Original Code
- You forgot to import the
csvmodule — this will throw an error when trying to usecsv.reader. - The loop
for i in len(self.cust)is invalid:len()returns an integer, so you can't iterate over it directly. Userange(len(self.cust))if you need index-based iteration, or just iterate over the list items directly. print(self.cust[1])inside the loop will repeatedly print the second element of the list, not each customer's unique data.
Improved Implementation
Instead of storing everything in a flat list, we'll use a dictionary where the customer name is the key — this makes lookups way easier and faster. Here's the revised code:
import csv class Rec: # Use a dictionary for fast lookups: key = customer name, value = full customer data cust_dict = {} def readCust(self): with open('customer.txt', 'r') as csv_file: # Skip extra spaces after commas in your CSV data reader = csv.reader(csv_file, skipinitialspace=True) for line in reader: # Store each customer's data under their name (line[1] is the name field) self.cust_dict[line[1]] = line return self.cust_dict def calculate_total(self, customer_name, quantity): # Check if the customer exists in our dictionary if customer_name in self.cust_dict: # Retrieve the unit price (line[3] from the CSV) and convert to float unit_price = float(self.cust_dict[customer_name][3]) total_cost = unit_price * quantity return f"Total cost for {customer_name}: {total_cost}" else: return f"Error: Customer '{customer_name}' not found in records!" # Example usage if __name__ == "__main__": record_handler = Rec() record_handler.readCust() # Test query for 'ciraj' with quantity 10 print(record_handler.calculate_total("ciraj", 10)) # Test a non-existent customer print(record_handler.calculate_total("john", 5))
Key Details
skipinitialspace=True: This handles the spaces after commas in your CSV (like8, ciraj, w , 8.5, 700) so we don't end up with extra spaces in customer names or values.- Dictionary-based storage: Using the customer name as the key lets us look up their data instantly, instead of looping through the entire list every time we need to check a name.
calculate_totalmethod: This takes the customer name and quantity, validates the customer exists, pulls the correct unit price, and returns the calculated total.
Testing with Your Data
When you run the example, you'll get this output:
Total cost for ciraj: 85.0 Error: Customer 'john' not found in records!
Which is exactly what you wanted — it finds 'ciraj', grabs the 8.5 price, multiplies by 10 to get 85.0.
内容的提问来源于stack exchange,提问作者Nitish A.
相关产品推荐
相关产品推荐

