KyleCrowley
KyleCrowley

Reputation: 930

Getting the next value within for loop

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

Upvotes: 0

Views: 511

Answers (4)

Peter DeGlopper
Peter DeGlopper

Reputation: 37364

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.

Upvotes: 0

Hugh Bothwell
Hugh Bothwell

Reputation: 56694

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)

Upvotes: 2

Hyperboreus
Hyperboreus

Reputation: 32449

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)

Upvotes: 1

aIKid
aIKid

Reputation: 28322

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

Upvotes: 1

Related Questions