【问题标题】:Getting 2nd Next Value in For Loop Python [duplicate]在 For 循环 Python 中获取第二个下一个值 [重复]
【发布时间】:2013-12-04 03:07:34
【问题描述】:

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

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

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

所以本质上,我只想遍历列表,当它找到一种交易类型时,下一个数字将是要加/减的金额。

我该怎么办?

【问题讨论】:

  • 你读过上一个问题的答案了吗?如果您已经阅读了它们,并且仍然需要提出这个问题,那么您甚至还没有理解第一个问题的答案。

标签: python for-loop


【解决方案1】:
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

【讨论】:

    【解决方案2】:

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

    元组列表

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      相关资源
      最近更新 更多