【问题标题】:How to enumerate through list with the first "index" reported as 1? (Python 2.4)如何枚举列表,第一个“索引”报告为 1? (Python 2.4)
【发布时间】:2011-11-23 00:26:53
【问题描述】:

我需要我的计数器从 1 开始。现在我有

for(counter, file) in enumerate(files):
    counter += 1
    //do stuff with file and counter

但必须有更好的方法,在 Python v2.4 中

【问题讨论】:

    标签: python python-2.4 enumerator


    【解决方案1】:

    发电机非常适合:

    def altenumerate( it ):
        return ((idx+1, value) for idx, value in enumerate(it))
    

    旧版python的简化版:

    def altenumerateOld( it ):
        idx = 1
        for value in it:
            yield (idx, value)
            idx += 1
    

    【讨论】:

    • 我想这不是什么大不了的事,除了风格/简单......我是这样做更好,还是只是counter+1?
    • 你最好升级到 Python 2.7。
    • IMO,这取决于您需要多久执行一次。如果你打算通过一堆循环分散counter+1,那么将这个想法抽象成一个生成器表达式或函数。如果是一次性的,什么都可以。
    【解决方案2】:

    在您使用过counter 的地方,可以使用counter + 1,而不是counter += 1

    或者:

    for counter, file in ((i + 1, f) for i, f in enumerate(files)):
        ...
    

    (Python 2.6 及更高版本有一些很棒的东西。如果可以,请尝试升级。)

    【讨论】:

      【解决方案3】:

      您可以制作自己的enumerate()

      def enumerate_1based(iterable):
          for index, item in enumerate(iterable):
              yield index+1, item
      

      或者,添加一个start 参数,使其与enumerate() 的更高版本一样工作。

      【讨论】:

        【解决方案4】:

        你可以使用zip():

        >>> enums = zip(range(1, len(files) + 1), files)
        >>> for index, val in enums:
            print index, val
        

        【讨论】:

        • 这是一个很酷的答案,但值得一提的是,旧版本的 python zip 和 range 将复制列表,并且可能需要 izip 和 xrange
        • 您现在可以交换它们,但请注意izip 将返回一个生成器。
        【解决方案5】:

        我是这样做的:

        #Emulate enumerate() with start parameter (introduced in Python 2.6)
        for i,v in (i+start,v for i,v in enumerate(seq)):
            //do stuff
        

        基本上,这是相同的,但却是一个独立的构造。

        【讨论】:

          【解决方案6】:
           for counter, item in enumerate(testlist):
              print(counter+1)
              print(item)
          

          【讨论】:

            【解决方案7】:

            在枚举方法中使用“start”参数来改变起始索引。

            for counter, file in enumerate(files, start=1):
                print(counter, file)
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2020-04-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2023-03-16
              相关资源
              最近更新 更多