You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过遍历列表索引获取从文件读取的客户数据中的名称及对应详情并实现查询计算

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 csv module — this will throw an error when trying to use csv.reader.
  • The loop for i in len(self.cust) is invalid: len() returns an integer, so you can't iterate over it directly. Use range(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 (like 8, 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_total method: 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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 18:22:32