2017-09-12 89 views
-1

我想在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與下面的代碼:

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循環中執行這些計算?

+6

看起來太像功課。 –

回答

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列中每個唯一帳戶的總和列表。

0

您可以按照@MrPyCharm的建議使用熊貓。如果你只需要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 
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

+0

謝謝。還有一件事情,如何計算每個賬戶的總交易次數? – habib

+0

而不是隻保存帳戶餘額,我會爲每個存儲餘額和交易計數的帳戶存儲一個字典: 'accounts [account_to] = {'balance':transaction_amount,'transaction_count':1}'然後增加交易計數每次你進行交易。 – philosopher