简体   繁体   中英

In Python, how do I restart a for loop within a while loop? The furthest out loop is a while loop that runs while r < y(length of integer list)

The integer list is essentially a random integer list of mostly integers in an excel file but there are some blocks of zeroes I want to identify. Ex. [3,3,3,0,0,4,0,6,0,0,7]. I just want to run through the list so that I can print: first block of zeroes start at index 3 and end at index 4, second block etc.

The list is a single column in excel, and spans thousands of rows.

The way I am doing that is with the following code:

r = 1
while r+1000 < y:
   for q in range(r,y-1):
      if sheet.cell_value(q,3) == '0':
          start = q
          print(str(start))
          for e in range(q,y-1):
              if sheet.cell_value(e,3) != 0:
                  r = e
                  print(str(end))
                  break
          break

The prints are there so I can check if it is going right. But what's happening now in the output is it never stops and only prints the start value.

You could do something similar to this to get a listing of where every group of 0's start and end.

>>> li = [3,3,3,0,0,4,0,6,0,0,7]
>>> tracking_zeros = False
>>>
>>> for i, n in enumerate(li):
...     if n == 0:
...         if not tracking_zeros:
...             print(f"start zeros: {i}")
...             tracking_zeros = True
...     else:
...         if tracking_zeros:
...             print(f"  end zeros: {i}")
...             tracking_zeros = False
...             
start zeros: 3
  end zeros: 5
start zeros: 6
  end zeros: 7
start zeros: 8
  end zeros: 10

Not counting single zeroes:

>>> tracking_zeros = False
>>>
>>> for i, n in enumerate(li):
...     if n == 0:
...         if not tracking_zeros and li[i+1] == 0:
...             print(f"start zeros: {i}")
...             tracking_zeros = True
...     else:
...         if tracking_zeros:
...             print(f"  end zeros: {i}")
...             tracking_zeros = False
...             
start zeros: 3
  end zeros: 5
start zeros: 8
  end zeros: 10

If the last item in the list is a 0, it'll throw an index error so you might need to account for that.

Could just append a non-zero value at the end before you do the loop to prevent that: li.append(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM