Skip to content Skip to sidebar Skip to footer

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,

Solution 1:

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

defpairs(lst):
    it = iter(lst)
    returnzip(it, it)

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

Solution 2:

An easy way, here.

for i, v in enumerate(l):
    ifv== '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])

Solution 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 inzip(data[::2], data[1::2]))
print(balance)

Or following your example:

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

Solution 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.

Post a Comment for "Getting The Next Value Within For Loop"