python循环转到if条件下的上一个字符串

2024-10-03 09:12:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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

如何用它来做呢

如果可能的话

  • while循环

解决这个问题的办法是什么

希望这是清楚明白的


Tags: thefordatastatusitthiscondition条件
1条回答
网友
1楼 · 发布于 2024-10-03 09:12:51

这是don buy while loop可以购买的

      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

相关问题 更多 >