如果您不喜欢那种奇怪的列表结构,我建议您采用不同的方法:
元组列表
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()