【问题标题】:Increment on certain condition with xrange()使用 xrange() 在特定条件下递增
【发布时间】:2012-06-16 05:22:14
【问题描述】:

对于有更多编程经验的人来说,这是一个非常简短且可能很容易回答的问题。如果满足某个条件,我想将我的计数器加一。我在for-loop 中使用xrange()。我可以手动增加i 还是必须自己构建计数器?

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

【问题讨论】:

    标签: python increment xrange


    【解决方案1】:
    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
    

    【讨论】:

      【解决方案2】:

      如果您打算经常这样做,这里有一个利用生成器上的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
      

      【讨论】:

      • 到目前为止,新人听说了send-方法。确实非常有趣。感谢您的意见,非常感谢!
      • 在 2.5 版本中引入。这是 PEP 的链接:docs.python.org/whatsnew/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多