【问题标题】:how to grab internal index of current loop in python when iter a list?迭代列表时如何在python中获取当前循环的内部索引?
【发布时间】:2012-06-21 07:33:39
【问题描述】:

我收到了listx =[1,2,3,4,5,6,7,8,9]

我想更改列表中的每第 N 个项目。例如,我想为每 2 项步骤进行修改,假设我想通过 +1 进行修改。 所以我想得到结果 = [1+1,2,3+1,4,5+1,6,7+1,8,9+1] =[2,2,4,4,6,6,8,8,9]

我可以通过使用 for-loop 来做到这一点,通过添加计数器变量,然后通过 counter%2==0 检查计数器。但这次我只是好奇使用单行语句。这是我想要的=

newlistx=[i+1 for i in listx]

newlistx=[i+1 if (__indexing__%step==0) else i for i in listx] 其中 step=2。

实际上,我可以像这样使用 list.index() 函数:

newlistx=[i+1 if listx.index(i)%2==0 else i for i in listx]

这个问题只有在所有项目都是唯一的情况下才有效,如果我得到的项目具有相同的值,那么 index() 将返回错误的值。

再次,我只是好奇是否可以获取一些内部索引或计数器(如果存在)。

【问题讨论】:

    标签: python loops indexing counter


    【解决方案1】:

    您可以使用enumerate 函数。

    newlist = [x + 1 if n % step == 0 else x
               for (n, x) in enumerate(oldlist)]
    

    enumerate 函数迭代一个序列并产生带有索引的对象。

    【讨论】:

    • 您对索引使用n,对列表项使用i,这让我感到畏缩。
    • 不错,正是我想要的。非常感谢。
    • @Markus:确实,我自己永远不会编写这样的代码。固定。
    【解决方案2】:
    new_list = [n + 1 if i & 1 else n for i, n in enumerate(listx)]
    

    【讨论】:

      猜你喜欢
      • 2011-03-20
      • 2014-09-12
      • 2014-01-24
      • 2014-05-02
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      相关资源
      最近更新 更多