0

A very short and probably easy to answer question for the ones with more programming experience. I want to increment my counter by one if a certain condition is met. I use xrange() in my for-loop. Can I manually increment i or do I have to build by own counter?

for i in xrange(1,len(sub_meta),2):
    if sub_meta[i][1] < sub_meta[i-1][1]:
            dict_meta[sub_meta[i-1][0]]= sub_meta[i][0]
    elif sub_meta[i][1] == sub_meta[i-1][1]:
            dict_meta[sub_meta[i-1][0]]= ''
            i += 1
LarsVegas
  • 6,522
  • 10
  • 43
  • 67

2 Answers2

4
i = 1
while i < len(sub_meta):
    if sub_meta[i][1] < sub_meta[i-1][1]:
        dict_meta[sub_meta[i-1][0]]= sub_meta[i][0]
    elif sub_meta[i][1] == sub_meta[i-1][1]:
        dict_meta[sub_meta[i-1][0]]= ''
        i += 1
    i += 2
eumiro
  • 207,213
  • 34
  • 299
  • 261
1

If you're planning on doing this often, here's an implementation that takes advantage of the send() method on generators:

def changeable_range(start, stop=None, step=1):
    if stop is None: start, stop = 0, start
    while True:
        for i in xrange(start, stop, step):
            inc = yield i
            if inc is not None:
                start, stop = i, stop + inc
                break
        else:
            raise StopIteration

Usage:

>>> myRange = changeable_range(3)
>>> for i in myRange: print i
... 
0
1
2
>>> myRange = changeable_range(3)
>>> for i in myRange:
...     print i
...     if i == 2: junk = myRange.send(2) #increment the range by 2
... 
0
1
2
3
4
Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
  • Newer heard of the `send`-method so far. Very interesting indeed. Thanks for your input, very much appreciated! – LarsVegas Jun 13 '12 at 10:57
  • It was introduced in version 2.5. Here is a link to the PEP: http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features – Joel Cornett Jun 13 '12 at 10:59