在For循环Python中获得第二个下一个值

时间:2013-12-04 03:07:35

标签: python for-loop

所以,扩展到我之前的一个问题。我对代码进行了一些更改,这使我不得不重新考虑如何解决问题。

重申一下,我有一个像这样的银行交易清单:

[08.10.17,D,520,08.11.01,W,20]

每个“交易”是三对,其中第一个是日期,第二个是类型(W或D),第三个是金额。

我需要做的是计算余额。

我想伪代码看起来像这样

for i in list:
    if i == 'D':
        bal = bal + (i+1)
    if i == 'W':
        bal = bal - (i+1)

基本上,我想循环遍历列表,当它找到一个事务类型时,下一个数字就是要加/减的数量。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

data = ['08.10.17','D','520','08.11.01','W','20']
for date, type, amount in zip(data[0::3], data[1::3], data[2::3]):
    print date, type, amount

这将输出:

08.10.17 D 520
08.11.01 W 20

您还可以执行以下操作,具有更好的性能:

def convert(stuff):
    it = iter(stuff)
    return zip(it, it, it)

for date, type, amount in convert(data):
    print date, type, amount

答案 1 :(得分:0)

如果你不喜欢那个奇怪的列表结构,我建议采用不同的方法:

元组列表

mylist = [('08.10.17','D',520),('08.11.01','W',20)]
bal = 0

for transaction in mylist:
    if transaction[1] == 'D':
        bal = bal + transaction[2]
    elif transaction[1] == 'W':
        bal = bal - transaction[2]

如上所述,@ sharth可以从原始列表结构中获取此列表结构:

data = ['08.10.17','D',520,'08.11.01','W',20]
mylist = zip(data[0::3], data[1::3], data[2::3])
# returns: [('08.10.17', 'D', 520), ('08.11.01', 'W', 20)]

<强>阵列

但是,通过使用numpy数组,您可以完全避免for循环:

import numpy as np

data = ['08.10.17','D',520,'08.11.01','W',20]
mylist = zip(data[0::3], data[1::3], data[2::3])

initial_balance = 0 # our initial balance

myarr = np.array(mylist) # generate an array based on our list

# create an array of the amounts with the appropriate sign; negative if 
# it is a withdraw, positive if a deposit
amounts = np.zeros(len(myarr)) 
amounts[:] = myarr[:,2] # grab the withdrawal/deposit amounts

signs = np.ones(len(myarr)) # an array of 1s (one for each transaction)
signs[np.where(myarr[:,1]=='W')] = -1 # make all the withdraws = -1 

amounts *= signs # multiply the amounts by appropriate signs

# our balance is now just our initial balance plus the sum of the transactions 
balance = initial_balance + amounts.sum()