【问题标题】:for loop but start at middle Pythonfor 循环,但从中间 Python 开始
【发布时间】:2021-09-25 21:04:06
【问题描述】:

有谁知道是否可以使用此代码从元素 ['d'] 而不是 ['a'] 开始? 我想可能会输入y+3,但这似乎不起作用。

list_ = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]
for y in list_:
    print(y)

此代码打印:

['a']
['b']
['c']
['d']
['e']
['f']
['g']
['h']

但我希望它打印出来:

['d']
['e']
['f']
['g']
['h']

【问题讨论】:

  • 查看文档中的列表切片:list[3:](也不要使用名称“列表”作为变量)。
  • 您可以创建列表的切片或使用索引
  • 请扩大问题以解释为什么你想从中间开始。可能有更直接的方法。

标签: python list loops


【解决方案1】:

使用islice

from itertools import islice

list_ = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]

for y in islice(list_, list_.index(['d']), None):
    print(y)

带有标志:

start = False

list_ = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]

for y in list_:
    if y == ['d']:
        start = True
    if start:
        print(y)

或者简单地使用切片:

list_ = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]

for y in list_[list_.index(['d']):]:
    print(y)

同时尝试重命名您的变量,因为 list 是 Python list 类。

【讨论】:

    【解决方案2】:
    list = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]
    for y in range(3,len(list)):
        print(list[y])
    

    这会输出你想要的

    【讨论】:

      【解决方案3】:

      您可以在循环中“切片”列表,如下所示:

      list = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]
      for y in list[3:]:
          print(y)
      

      或者,您可以使用第一个参数作为起点的范围。

      for y in range(3, len(list)):
          print(list[y])
      

      【讨论】:

        【解决方案4】:

        一种解决方案是在迭代列表之前对其进行切片:

        for y in list[3:]:
            print(y)
        

        【讨论】:

          【解决方案5】:

          我不知道你是不是想从中间开始,但不管有多少个iten,你都可以这样做:

          list_ = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]
          
          for y in list_[int(len(list_)/2):]:
              print(y)
          

          它将检查iten的数量并将其除以2并将其转换为整数值。循环将从那里开始。

          【讨论】:

            【解决方案6】:

            itertools.dropwhile 提供此功能。

            from itertools import dropwhile
            
            
            for x in dropwhile(lambda x: x != ['d'], list):
                print(x)
            

            【讨论】:

              【解决方案7】:

              尝试使用startstop 内置在range 中:

              list_ = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']]
              for y in range(3, len(list_)):
                  print(list_[y])
              

              输出:

              ['d']
              ['e']
              ['f']
              ['g']
              ['h']
              

              【讨论】:

                猜你喜欢
                • 2021-12-18
                • 2012-12-12
                • 2021-10-18
                • 2017-05-24
                • 1970-01-01
                • 1970-01-01
                • 2013-06-22
                • 1970-01-01
                • 2012-08-31
                相关资源
                最近更新 更多