python计算当前账户余额

2024-09-30 14:31:21 发布

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

我想用Python完成这个任务。在

您将获得一个包含事务列表的CSV文件示例。在

  • 第一列是汇款人的账号
  • 第二栏是金额,以及
  • 第三栏是收款人的账号。在

您的任务是解析CSV,并计算每个帐号的当前余额。在

提交一个接受单个参数(事务CSV文件的位置)的python脚本,并打印出每个帐户的余额。在

CSV文件模式:

from, amount, to
314, 470.21, 275
12, 1788.98, 149
316, 2949.53, 314
5, 2193.48, 454
314, 1402.76, 371
82, 1212.1, 4420

我用以下代码呈现了这个CSV文件:

^{pr2}$

如何计算每个帐户的当前余额?在

每个账户都进行多次交易。在

例如:如果帐号314在from列中,它将给定的金额发送给to列中的帐号。{cd1>必须在上一列中找到余额。在

如何在for循环中进行这些计算?在


Tags: 文件csvtofrom示例列表参数帐户
3条回答

你可以按照@MrPyCharm的建议使用熊猫。如果只需要清除python解决方案而不需要额外的依赖项,可以这样做:

data = [
    [314, 470.21,  275],
    [12,  1788.98, 149],
    [316, 2949.53, 314],
    [5,  2193.48, 454],
    [314, 1402.76, 371],
    [82, 1212.1,  420],
]

balances = {}
for from_, value, to_ in data:
    balances[from_]  = - value + balances.get(from_, 0) 
    balances[to_]  = value + balances.get(to_, 0) 

for user_id, balance in balances.items():
    print('Id: {}, balance: {}'.format(user_id, balance))

输出:

^{pr2}$

我建议对此使用dictionary,其中键表示帐号。在

import csv

def csv_data(path):

    accounts = {}  # storage of the account balances

    with open(path) as csv_file:
        readCSV = csv.DictReader(csv_file)

        for line in readCSV:
            account_from = int(line['from'])
            account_to = int(line['to'])
            transaction_amount = float(line['amount'])

            # subtract from old account
            if account_from in accounts:
                accounts[account_from] -= transaction_amount
            else:
                accounts[account_from] = (0-transaction_amount)

             # add to new account
             if account_to in accounts:
                accounts[account_to] += transaction_amount
             else:
                accounts[account_to] = transaction_amount

    for account in accounts:
        print("{}: \t{}".format(account, accounts[account]))

csv_data('transactions.csv')

其输出如下:

^{pr2}$

请注意,事务处理应该始终遵循ACID-Properties。在

这可能不是一个理想的答案,但您可以使用pandas来实现这一点。在

import pandas as pd

df = pd.read_csv('/path/to/the/file')
total_for_each_account = [df[df['from'] == account]['amount'].sum() for account in df.from.unique()]

返回from列中每个唯一帐户的总和的列表。在

相关问题 更多 >