简体   繁体   English

Python 在嵌套 for 循环中编写嵌套 if-else 的有效方法

[英]Python efficient way to write nested if-else inside nested for-loop

I'm working on a code challenge in which I have to reduce the execution time as much as possible, the only thing I able to find where I can make an improvement is a nested if-else statement inside a nested for-loop but I'm not sure how it can be improvided.我正在处理一个代码挑战,我必须尽可能减少执行时间,我唯一能找到可以改进的地方是嵌套 for 循环中的嵌套 if-else 语句,但我'不知道它是如何即兴创作的。

Here's my code:这是我的代码:

mat = [[0] * n] * n
count = 0
for i in range(n,0,-1):
    count += 1
    for j in range(i,n+1,1):
        if i == j:
            pass
        else:
            if getEnemyStatus(mat, i, j):
               break
            else:
                if isEnemy(enemyDict, i, j):
                    setStatus(mat, i, j)
                    break
                else:
                    count += 1

value of n can be from 1 to 10^5 n的值可以从 1 到 10^5

You can skip the first if condition by starting with i+1 in range您可以从rangei+1开始跳过第一个if condition

for j in range(i+1, n+1, 1):
   # code here

Second, nested if else condition should be avoided with elif for reading purpose.其次,出于阅读目的,应避免使用elif嵌套if else条件。

Update code should be like:更新代码应该是这样的:

mat = [[0] * n] * n
count = 0
for i in range(n,0,-1):
    count += 1
    for j in range(i + 1, n + 1, 1):
        if getEnemyStatus(mat, i, j):
            break
        elif isEnemy(enemyDict, i, j):
            setStatus(mat, i, j)
            break
        else:
            count += 1

NOTE : Also if you can set the status setStatus in your isEnemy function then you can get more cleaner code:注意:此外,如果您可以在isEnemy function function 中设置状态setStatus ,那么您可以获得更清晰的代码:

mat = [[0] * n] * n
count = 0
for i in range(n,0,-1):
    count += 1
    for j in range(i + 1, n + 1, 1):
        if getEnemyStatus(mat, i, j) or isEnemy(enemyDict, i, j):
            break
        count += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM