【问题标题】:How to skip indexes?如何跳过索引?
【发布时间】:2018-09-13 14:55:57
【问题描述】:

我在创建代码的最后一部分时遇到问题。例如,我正在尝试使列表正常迭代到第 3 项,然后检查该项目是否为 3 和其他条件(现在不重要),然后将索引更改为从示例 10 开始迭代。

我做了很多尝试,但似乎没有用。

li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
for i in range(0,len(li)):
    print(i)
    if i == 3: #along with other condition
        def g(li):
            global i
            i = li[9]
        g()
        print(i)

【问题讨论】:

  • 为什么要使用嵌套函数?此外,Python for 循环与 Java/C for 循环不同; i 的值将在下一次迭代中被替换,而不是修改。也许改用while 循环?

标签: python list skip


【解决方案1】:

您可以使用continue 语句:

li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
for i in range(len(li)):
    if 3 <= i < 10: #along with other condition
        continue
    print(i)

打印i时输出:

0,1,2,10,11,12,13,14,15

打印li[i]时输出:

1,2,3,11,12,13,14,15,16

continue 语句将您带到循环的开头,忽略以下所有条件。
你可能想看看loop control statements

【讨论】:

    【解决方案2】:

    for 循环不是必需的。如果您对使用 3rd 方库感到满意,可以使用 NumPy:

    import numpy as np
    
    A = np.array(li)
    
    res = A[np.r_[:4, 9:len(A)]]
    
    # array([ 1,  2,  3, 10, 11, 12, 13, 14, 15, 16])
    

    或者使用常规 Python,您可以使用 slice 对象:

    from operator import itemgetter
    from itertools import chain
    
    slices = (slice(0, 4), slice(9, None))
    
    res = list(chain.from_iterable(itemgetter(*slices)(li)))
    
    # [1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16]
    

    【讨论】:

      【解决方案3】:

      您正在将 i 的值设置为 for 循环中的某个值。在 for 循环的每次迭代开始时,python 将 i 的值更新为它正在迭代的可迭代对象中的下一个值。因此,您的价值将丢失且未被使用。

      一种解决方案是像这样使用另一个变量 (skip_until):

      lst = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
      skip_until = -1
      for i in range(len(lst)):
          if i == 3:
              skip_until = 9
          if skip_until >= i:
              continue      
          print((i, lst[i]))
      

      输出:

      (0, 1) (1, 2) (2, 3) (10, 11) (11, 12) (12, 13) (13, 14) (14, 15) (15, 16)

      【讨论】:

        【解决方案4】:
        li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
        condition3_reached = False
        condition10_reached = False
        for i in li:
            print(i)
            if conditition3_reached and not condition10_reached and i != 10:
                continue
            if condition3_reached and i == 10:
                condition10_reached = True
            if i == 3 and (#along with other condition):
                condition3_reached = True
                print(i)
            else:
                do_some_new_thing_for_10_onwards()
        

        这是实现您想要的简单方法。我担心的是它不可扩展

        【讨论】:

          【解决方案5】:

          应该像这样使用 continue:

          li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
          for i in range(0,len(li)):
              if i in range(3, li[9]):
                  continue
              print(i)
          

          【讨论】:

            【解决方案6】:

            最简单易读的方法是通过使用while 而不是for 循环,如下所示。

            li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
            i = 0
            while i < len(li):
                print(i)
                if i == 3:
                    i = 10
                    print(i)
                i += 1 # increment i at the end of the loop
            

            【讨论】:

              【解决方案7】:

              我试着理解你说的话,我写了这段代码

              li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
              def k(pos = 0):
                  for i in li[pos:]:
                      print(i)
                      if li.index(i) == 3: #along with other condition
                          return k(pos = 9)
              k()
              

              【讨论】:

              • 当然,你可以改变你想要的位置和条件
              【解决方案8】:

              使用 Python for 循环实际上无法实现您想要做的事情,它比 Java/C 风格的 for (initializer; step; condition) 循环要少,但更像是 foreach (iterable) 循环,其中可迭代恰好是range 在你的情况下。

              因此,每当您在循环中执行i = ...i 是来自for 循环的变量)时,i 将在循环的下一次迭代中被新值覆盖(未修改) .

              相反,您可以使用稍长的while 循环:

              i = 0
              while i < len(li):
                  print(i)
                  if i == 3: #along with other condition
                      def g(li):
                          global i
                          i = li[9]
                      g(li)
                  else:
                      i += 1
              

              另请注意,嵌套函数 g 显然没有任何用途,可以删除,尽管实际代码中的情况可能不同。

              i = 0
              while i < len(li):
                  print(i)
                  if i == 3: #along with other condition
                      i = li[9]
                  else:
                      i += 1
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2023-01-17
                • 2023-03-07
                • 1970-01-01
                • 1970-01-01
                • 2014-05-31
                • 2012-03-24
                • 2022-09-23
                • 2018-05-28
                相关资源
                最近更新 更多