在列表迭代中回到早期索引

-1 投票
3 回答
61 浏览
提问于 2025-04-12 04:06

我有一个循环在处理一个列表:

MyList = ["test", "test2", "test3", "test4", "test5", "test6", "test7"]

for item in MyList:
    print(item) # output: [test, test2, test3, test4, test5, test6, test7]
    if item == "test7":
        pass  # ?

现在在这个循环里,如果遇到 item == "test7",我想回到第三个项目("test3"),然后继续计数。

我该怎么做呢?

我必须使用 for 循环,不能使用 while 循环。

3 个回答

-3

你可以使用索引和循环的范围。

MyList = ["test", "test2", "test3", "test4", "test5", "test6", "test7"]

for i in range(len(MyList)):
    print(MyList[i]) # output: [test, test2, test3, test4, test5, test6, test7]
    if item == "test7":
       i = i - 1

#所以如果你想要前一个元素,当 i 不等于 0 的时候,可以用 MyList[i-1] 来获取

pass # ?

-2

试试这个...我不知道这是否是你想要的。

MyList = ["test", "test2", "test3", "test4", "test5", "test6", "test7"] starting_index = 2 

for i, item in enumerate(MyList):
    print(item)
    if item == "test7":
        for j in range(starting_index, len(MyList)):
           
            print("Processing:", MyList[j])
        break

-2

把 new_start_index 改成你想要的值,然后再写一个 for 循环就行了。

MyList = ["test", "test2", "test3", "test4", "test5", "test6", "test7"]

for item in MyList:
    print(item)
    if item == "test7":
        new_start_index = 3
        # Continue the loop from the new_start_index
        for new_item in MyList[new_start_index:]:
            print(new_item)

撰写回答