Python:执行for循环的索引

2024-03-29 13:56:16 发布

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

在python中,有没有某种方法可以在for循环中向前移动索引?例如,如果我在遍历一个字符串并找到我要查找的字符,那么在For循环的下一次迭代中,我可以从该位置开始读取吗?在

比如,在读取x之后,一直读到y,然后在下一次迭代中从y后面的位置开始:

for i in range(len(myString)):
  if myString[i] == 'x':
    j = i + 1
    while( myString[j] != '\n' ):
      if( myString[j] == 'y' ):
        i = j + 1  # start at position following y in string on the next iteration
      j = j + 1

或者我必须使用while循环来实现这一点?在


Tags: 方法字符串inforlenifpositionrange
3条回答

您可以尝试使用无限循环:

while true:
   if i >= len(myString): # Exit condition
      break

   # do something with myString[i]

   # set i as you want

现在,实际上您仍然在这里使用while循环,但我认为这在精神上更接近于您的想法:

def myrange(limit=0):
    counter = 0
    while counter < limit:
        next = yield counter
        try:
            counter = int(next) - 1
        except TypeError:
            counter += 1    


mylist = ['zero', 'one', 'two', 'five', 'four']       
my_iter = myrange(len(mylist))

for i in my_iter:
    print(mylist[i])
    if mylist[i] == 'five':
        print('  three, sir!  ')
        mylist[i] = 'three!'
        my_iter.send(i)
    elif mylist[i] == 'four':
        print("Don't count that number!")

这是因为生成器具有^{}函数。它们允许您向生成器发送一个值,然后生成器可以按其希望的方式使用该值。请注意,当您在生成器上调用.send()时,它将生成下一个值(因此,当我们调用my_iter.send(i)时,它实际上是yield生成下一个值。这就是为什么我们称counter = int(next) - 1。另一种方法是将-1放入for循环中。在

在这个示例代码中,可以使用字符串而不是list。它在列表的剩余部分中找到第一个x,然后在“x”之后找到第一个y,依此类推

#mylist = [list to search]
i = 0
while true:
    list_to_search = mylist[i:]
    if 'x' not in list_to_search:
        break
    j = list_to_search.index('x')
    if 'y' not in list_to_search[j+1:]:
        break
    i = list_to_search.index('y')
    (x_pos,y_pos)  = (j,i)
    #your code

相关问题 更多 >