Python在文本fi中搜索最富有的客户

2024-09-28 22:33:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写代码时遇到了一些问题。我试图在一个银行余额最大的文件中找到客户。文本文件的示例如下:

12345,美国能源部约翰,300.001998-01-30

23456,简,Doe,1200.501998-02-20

在这种情况下,无名氏有最大的余额,我想打印她的整个文件/行。我该怎么办?以下是我目前掌握的情况:

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

谢谢你的帮助!你知道吗


Tags: 文件代码info示例客户line情况银行
3条回答

您可以定义一个“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))

格尼布勒的回答可以这样写,我认为:

def get_best_customer(customer_file):

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

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,而不是附加到它。你知道吗

相关问题 更多 >