计算python中帐户的当前余额

时间:2017-09-12 07:11:27

标签: python csv

我想用Python完成这项任务。

您将获得一个包含交易列表的示例CSV文件。

  • 第一列是钱来自的人的帐号,
  • 第二列是金额,
  • 第三栏是钱的人的帐号。

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

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

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文件:

import csv

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

        for line in readCSV:
            col_from = line['from']
            col_to = line['to']
            col_amount = line['amount']
            print(col_from, col_amount, col_to)

csv_data('transactions.csv')

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

每个帐户都进行了多笔交易。

例如:如果帐号314在from列中,则会将给定金额发送到to列中的帐号。如果在from列中找到此帐号,则必须添加以前的余额。

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

3 个答案:

答案 0 :(得分:0)

这可能不是一个理想的答案,但您可以使用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列中每个唯一帐户的总和列表。

答案 1 :(得分:0)

您可以按照@MrPyCharm的建议使用pandas。如果你需要clear-python解决方案wuthout额外的依赖项,你可以这样做:

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))

输出:

Id: 314, balance: 1076.5600000000002
Id: 275, balance: 470.21
Id: 12, balance: -1788.98
Id: 149, balance: 1788.98
Id: 316, balance: -2949.53
Id: 5, balance: -2193.48
Id: 454, balance: 2193.48
Id: 371, balance: 1402.76
Id: 82, balance: -1212.1
Id: 420, balance: 1212.1

答案 2 :(得分:0)

我建议使用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')

以下输出:

420:    1212.1
5:      -2193.48
454:    2193.48
371:    1402.76
12:     -1788.98
82:     -1212.1
275:    470.21
149:    1788.98
314:    1076.56
316:    -2949.53

请注意,交易应始终遵循ACID-Properties