迭代完成后运行代码

时间:2016-02-29 10:06:47

标签: python python-3.x

也许我在想困难,但我想知道在for循环结束后是否可以执行代码?

我需要一种机制,它知道循环已经完成并在for循环结束时执行代码。

简单示例:

numbers = ['1','2','3','4','5']
length_numbers = len(numbers)

for i in range(0, length_numbers):
    print(i)
    if i == length_numbers + 1:
        print("yep list is finished and execute code below")
        # .... <-- code will be placed here

这不起作用,因为i值永远不会成为值5.我确信有一种简单的方法可以解决这个问题。谁能告诉我如何实现这一目标?也许我应该改变构造而不是使用for循环?

6 个答案:

答案 0 :(得分:4)

您可以使用ak_bmsc声明。

else

答案 1 :(得分:2)

因为在python中编号系统从0开始,如果你想让上面编写的代码工作,你需要将if i == length_numbers + 1更改为减1 - if i == length_numbers - 1,代码将作为你想要它。

所以对你的例子来说:

numbers = ['1','2','3','4','5']
length_numbers = len(numbers)

for i in range(0, length_numbers):
    print(i)
    if i == length_numbers - 1: # change to minus here
        print("yep list is finished and execute code below")
        # .... <-- code will be placed here

答案 2 :(得分:2)

如果您的号码已修复,则代码可能会有效。

只需替换

    if i == length_numbers + 1:

    if i == length_numbers - 1:

即使数字不固定。你只需使用len()函数&amp;当你从零开始循环时,你可以检查i的值

    length_num = len(numbers) # get the length of numbers

    if i == length_num - 1  # check if i reached last val
        # stuff you want to do 

希望这有帮助

答案 3 :(得分:1)

为什么不使用if i == length_numbers - 1:所以代码会在最后一次迭代结束时执行(请注意range(0, length_numbers) = [0, 1, ..., length_numbers - 1])?或者只是将代码放在for循环之后。

像这样:

numbers = ['1','2','3','4','5']
length_numbers = len(numbers)
for i in range(0, length_numbers):
    print(i)
    if i == length_numbers - 1:
        print("yep list is finished and execute code below")
        # .... <-- code will be placed here

或者这个:

numbers = ['1','2','3','4','5']
length_numbers = len(numbers)
for i in range(0, length_numbers):
    print(i)
print("yep list is finished and execute code below")
# .... <-- code will be placed here

答案 4 :(得分:1)

简单的方法怎么样?

numbers = ['1','2','3','4','5']
length_numbers = len(numbers)

for i in range(0, length_numbers):
    print(i)

print("yep list is finished and execute code below")

答案 5 :(得分:0)

如果len(数字)== i + 1:

,请点击