【问题标题】:python loop go to previous string under if condictionpython循环在if条件下转到上一个字符串
【发布时间】:2020-05-22 00:04:34
【问题描述】:

我有一个 for 循环来处理来自输入的数据 当它找到开始索引行的条件时,我怎么能在它之前减去两行

# this is the data sample

Candra Insley
Ivette Ralston
Florentina Bohon
Natalie Underhill
Shoshana Risinger
Melony Hulsey
Klara Warren
Corrina Broderick
Susana Vitti
Susy Seidman
Chris Deen
Mason Nebel
Tawanda Riccio
Shameka Schmitmeyer
Robert Longacre
Floria Padro
Julius Gelman
Kyung Barnard
Freida Manville
Wendy Bolduc

这里是代码

status = request.form['data']
  status = str(status).split('\n')
  for i in status:
    if len(i) < 2:
      continue
    print i
    data = i[0]
    condition = 'Shameka Schmitmeyer'
    if condition in data:
      print 'found it'
      condition = ''
      i -= 2 # here it will subtract the current data index 2 it will go back two line to this "Mason Nebel" data and start the for from it and continue
    print data
#output it should be like

Candra Insley
Ivette Ralston
Florentina Bohon
Natalie Underhill
Shoshana Risinger
Melony Hulsey
Klara Warren
Corrina Broderick
Susana Vitti
Susy Seidman
Chris Deen
Mason Nebel
Tawanda Riccio
found it
Shameka Schmitmeyer

这里当条件为真时,它会返回两行并从“Mason Nebel”这个值继续

继续时的样子

Mason Nebel
Tawanda Riccio
Shameka Schmitmeyer
Robert Longacre
Floria Padro
Julius Gelman
Kyung Barnard
Freida Manville
Wendy Bolduc

如何用for来做

如果可能的话

  • while 循环

解决办法是什么

希望这很容易理解

【问题讨论】:

  • 我不完全确定我理解您要做什么,但如果您切换到 while 循环,您应该能够像这样更改当前循环变量。
  • 很酷我怎么能用while循环来做到这一点
  • 你真的应该修复你的格式,这很难理解。我也不确定你在问什么,你的问题的输入是什么,预期的输出是什么?

标签: python python-3.x python-2.7 for-loop while-loop


【解决方案1】:

这是可以不要在while循环中购买的

      status = request.form['data']
      status = str(status).split('\n')

      i = 0
      while i <= len(status):

        element = status[i]
        if len(status[i]) < 2:
          continue

        datalist = element.strip().split('|')
        print(datalist)
 
        data = datalist[0]
        condition = 'Shameka Schmitmeyer'

        if condition in data:
          print('found it')
          condition = ''
          i -=2

        print(data)
        i +=1

输出

Candra Insley
Ivette Ralston
Florentina Bohon
Natalie Underhill
Shoshana Risinger
Melony Hulsey
Klara Warren
Corrina Broderick
Susana Vitti
Susy Seidman
Chris Deen
Mason Nebel
Tawanda Riccio
found it
Shameka Schmitmeyer
Mason Nebel
Tawanda Riccio
Shameka Schmitmeyer
Robert Longacre
Floria Padro
Julius Gelman
Kyung Barnard
Freida Manville
Wendy Bolduc

【讨论】:

    猜你喜欢
    • 2014-05-21
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多