Check statement for a loop only once

怎甘沉沦 提交于 2021-02-11 07:20:39

问题


Let’s say I have following simple code:

useText = True

for i in range(20):
    if useText:
        print("The square is "+ str(i**2))
    else:
        print(i**2)

I use the variable useText to control which way to print the squares. It doesn’t change while running the loop, so it seems inefficient to me to check it every time the loop runs. Is there any way to check useText only once, before the loop, and then always print out according to that result?

This question occurs to me quite often. In this simple case of course it doesn’t matter but I could imagine this leading to slower performance in more complex cases.


回答1:


The general structure of your program is to loop through a sequence and print the result in some manner.

In code, this becomes

for i in range(20):
    print_square(i)

Before the loop runs, set print_square appropriately depending on the useText variable.

if useText:
    print_square = lambda x: print("The square is" + str(x**2))
else:
    print_square = lambda x: print(x**2)

for i in range(20):
    print_square(i)

This has the advantage of not repeating the loop structure or the check for useText and could easily be extended to support other methods of printing the results inside the loop.




回答2:


The only difference that useText accomplishes here is the formatting string. So move that out of the loop.

fs = '{}'
if useText:
    fs = "The square is {}"

for i in range(20):
    print(fs.format(i**2))

(This assumes that useText doesn't change during the loop! In a multithreaded program that might not be true.)




回答3:


If you are not going to change the value of useText inside the loop, you can move it outside of for:

if useText:
    for i in range(20):
        print("The square is "+ str(i**2))
else:
    for i in range(20):
        print(i**2)



回答4:


We can move if outside of for since you mentioned useText is not changing.




回答5:


If you write something like this, you're checking the condition, running code, moving to the next iteration, and repeating, checking the condition each time, because you're running the entire body of the for loop, including the if statement, on each iteration:

for i in a_list:
    if condition:
        code()

If you write something like this, with the if statement inside the for loop, you're checking the condition and running the entire for loop only if the condition is true:

if condition:
    for i in a_list:
        code()

I think you want the second one, because that one only checks the condition once, at the start. It does that because the if statement isn't inside the loop. Remember that everything inside the loop is run on each iteration.



来源:https://stackoverflow.com/questions/34572259/check-statement-for-a-loop-only-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!