2012-06-13 11 views
0

對於具有更多編程經驗的人來說,這是一個非常短暫且很容易回答的問題。如果滿足某個條件,我想增加一個計數器。我在我的for -loop中使用了xrange()。我可以手動增加i還是必須通過自己的櫃檯來建造?用xrange()增加一些條件()

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 

回答

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 
+0

所以,是的,我必須建立自己的櫃檯。這就是我認爲... – LarsVegas

1

如果你在經常做這個規劃,下面是對發電機組採取send()方法的優點的實現:

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 

用法:

>>> 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 
+0

到目前爲止,最近聽說過「發送」方法。確實非常有趣。感謝您的意見,非常感謝! – LarsVegas

+0

它是在2.5版本中引入的。以下是PEP的鏈接:http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features –