【问题标题】:How to reset the index number of for loop in python如何在python中重置for循环的索引号
【发布时间】:2020-04-10 08:27:37
【问题描述】:
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重新开始迭代。让我们考虑条件变为Truex = 20

要重置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。任何人都可以提出任何好的解决方案。请帮忙。谢谢

【问题讨论】:

标签: python for-loop


【解决方案1】:

您需要注意不要通过重置索引来创建无限循环。您可以使用带有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

【讨论】:

    【解决方案2】:

    不要使用for 循环,而是使用while 循环。

    以下for 循环(不起作用):

    for i in range(n):
        ...
        if condition:
            i = 0
    

    应替换为:

    i = 0
    while i < n:
        ...
        if condition:
            i = 0
        else:  # normal looping
            i += 1
    

    或者,continue:

    i = 0
    while i < n:
        ...
        if condition:
            i = 0
            continue
        i += 1
    

    当使用while 时,请注意可能的无限循环。 避免无限循环的可能策略包括使用标志或包括一个额外的计数器来限制最大迭代次数,而不管主体中实现的逻辑如何。

    【讨论】:

    • 在while循环中n是什么
    • @SAndrew 对不起,我认为从“除了不工作 for 循环之外的等效项”中很清楚。 nrange()for 循环代码中的参数,即如果condition 永远不会是True,循环将执行的次数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    相关资源
    最近更新 更多