【问题标题】:Python - Searching for the Richest customer in a text filePython - 在文本文件中搜索最富有的客户
【发布时间】:2026-02-11 02:25:02
【问题描述】:

我正在编写的一些代码存在一些问题。我试图在银行余额最大的文件中找到客户。文本文件的一个例子是:

12345,John,Doe,300.00,1998-01-30

23456,Jane,Doe,1200.50,1998-02-20

在这种情况下,Jane Doe 的余额最大,我想打印她的整个文件/行。我该怎么办?到目前为止,这是我所拥有的:

def get_best_customer(customer_file):

    customer_file.seek(0)
    richest = 0
    customer_info = []

    for line in customer_file:
        line = customer_file.readline().strip()
        balance = line.split(',')
        if balance > richest:
            customer_info.append(balance)

    return customer_info

感谢您的帮助!

【问题讨论】:

    标签: python file file-io python-3.x


    【解决方案1】:

    您可以定义一个“key”函数,它接受一行并返回money 字段。那么max就可以直接使用了

    def get_best_customer(customer_file):
    
        customer_file.seek(0)
    
        def get_money(line):
            return float(line.split(',')[3])
    
        print(max(customer_file, key=get_money))
    

    【讨论】:

      【解决方案2】:

      line.split(',') 返回一个列表字符串 --> ['23456', 'Jane', 'Doe', '1200.50', '1998-02-20']。然后你需要转换你感兴趣的字段:

      line = customer_file.readline().strip()
      data = line.split(',')
      balance = float(data[3])
      

      这应该会让你继续前进。您仍然需要设置richest,进行比较,并且可能只需将customer_info 设置为data,而不是附加到它。

      【讨论】:

        【解决方案3】:

        Gnibbler 的回答我觉得可以这样写:

        def get_best_customer(customer_file):
        
            with open(customer_file, "r") as f:
                return max(f, key=(lambda l: float(l.strip().split(",")[3])))
        

        【讨论】:

        • 是的,但它更难调试并且不可能进行单元测试。如果有 一些特殊情况来处理这个 lambda,很快就会变得混乱。