Getting the next value within for loop

自作多情 提交于 2019-12-31 05:52:40

问题


I am writing a program in Python that reads in bank data from a file and stores it in data structures for output at a later time.

I have a list that stores the transactions like

D,520,W,20,D,100

Where the letter is the transaction type (Withdrawl or Deposit) and the numbers are the amount.

I have a for loop that will calculate the balance, but I am having trouble getting to the next element.

Essentially what I want to do is:

for item in theList:
    if item == 'D':
        balance = balance + int(NEXT_ITEM)
    if item == 'W':
        balance = balance - int(NEXT_ITEM)

Thanks for the help


回答1:


data = 'D,520,W,20,D,100'.split(',')

def pairs(lst):
    it = iter(lst)
    return zip(it, it)

balance = 0
for trans,amt in pairs(data):
    if trans == 'D':
        balance += int(amt)
    else:
        balance -= int(amt)
print(balance)



回答2:


An easy way, here.

for i, v in enumerate(l):
    if v == 'D':
        balance = balance + int(l[i+1])

Or just read two items at once:

for i in range(0, len(l), 2):
    sl = l[i:i+2]
    if sl[0] == 'W':
        balance = balance - int(sl[1])



回答3:


data = 'D,520,W,20,D,100'.split(',')
it = iter(data)
balance = sum({'W': -1, 'D': +1}[item] * int(next(it)) for item in it)
print(balance)

Create an iterator and iterate over it. Then you can call next to get the next item.


Or without the need of next, by pairing the items of the list via zip:

data = 'D,520,W,20,D,100'.split(',')
balance = sum({'W': -1, 'D': +1}[a] * int(b) for a, b in zip(data[::2], data[1::2]))
print(balance)

Or following your example:

theList = 'D,520,W,20,D,100'.split(',')
theIterator = iter(theList)
balance = 0
for item in theIterator:
    if item == 'D':
        balance = balance + int(next(theIterator))
    if item == 'W':
        balance = balance - int(next(theIterator))
print(balance)



回答4:


If your data is pairs of a transaction type code and a transaction amount, the natural data type is a list of dictionaries or a list of tuples. Or named tuples if you like. Other answers are showing how you can work around your choice of a flat list, but I think the best fix is to keep the bundling of the associated elements in the list you create from your file:

data = [('D', 520), ('W', 20), ...]

Or if your data is as simple as shown here, a list of signed numbers. Probably of the decimal.Decimal type unless you're dealing with whole dollars only.

I am assuming from your description that the creation of the list from your file is under your control. If not, I think Hugh Bothwell's answer is the cleanest way to adjust.



来源:https://stackoverflow.com/questions/20365480/getting-the-next-value-within-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!