gpt4 book ai didi

python - 如何在python中重置for循环的索引号

转载 作者:行者123 更新时间:2023-12-02 00:04:18 24 4
gpt4 key购买 nike

for x in range(len(pallets_data_list)):
"""
SOME CODE
"""
if pallets_data_list[x]['data_id'] == 32:
# Go back and search again in for loop

在上面的代码中,我有一个 for 循环遍历 pallets_data_list。在这个 for 循环中,如果条件变为 True,我需要返回到 for 循环并从 0 开始再次迭代。让我们考虑一下在 x = 20 时条件变为 True

要重置 x,我将其设置为 0,然后使用 continue,如下所示:

    if pallets_data_list[x]['data_id'] == 32:
# Go back and search again in for loop
x = 0
continue

使用 continue,它返回到 for 循环,但 x 未重置并从 21 开始迭代.有什么办法,我可以将 x 重新设置回 0。任何人都可以提出任何好的解决方案。请帮忙。谢谢

最佳答案

您需要注意不要通过重置索引来创建无限循环。您可以使用带有 found 标志的 while 循环来避免这种情况:

pallets_data_list = [1, 4, 6, 32, 23, 14]

x = 0
found = False
while x < len(pallets_data_list):
print(pallets_data_list[x])
if not found and pallets_data_list[x] == 32:
found = True
x = 0
continue
x += 1

输出:

1
4
6
32
1
4
6
32
23
14

关于python - 如何在python中重置for循环的索引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61136568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com