假设我正在寻找 some_array
的索引,其中 some_array
等于 target
。我知道 python 具有列表理解和 np.where()
,两者都可以很好地满足我的目的。但也假设我想用 if-elif-else
语句或 for
循环来完成它。如果数组的长度为 3,则实现如下所示:
if some_array[0]==target:
return 0
elif some_array[1]==target:
return 1
else:
return 2
for i in range(3):
if some_array[i]==target:
return i
那么,什么时候最好在 if-elif-else 语句上使用 for 循环?我最感兴趣的是它在 python 和 C 中的应用,即 switch-cases
。
我的子问题是:
- 编译器(或者在 Python 中,
numba
或cython
)是否从for
循环切换到switch-cases
如果感觉另一种方法更快,反之亦然? - 是否有普遍接受的良好编码实践建议
if-elif-else
语句的最大长度以提高可读性? - 数组的长度或迭代次数是否存在其中一个性能优于另一个的阈值?
如果之前有人问过这个问题,我深表歉意。我尝试查看建议的问题,但对我的目的没有帮助。
提前致谢!
最佳答案
So, when is it better to use a for loop over if-elif-else statement?
对于此特定目的,循环总是比if
-else if
-else
链更清晰。这是选择循环的充分理由,除非在极不可能的情况下,您将性能瓶颈追溯到这样的循环并且发现通过更改为if
可以缓解这种情况>.
- Do the compilers (or in Python's case, numba or cython) switch from a for loop to switch-cases or vice versa if it feels like the other approach is faster?
循环展开是一种标准优化,许多 C 编译器会在认为它会产生改进时执行。一个短循环可能会完全展开而不存在,这实际上就是您所询问的转换。
我不知道编译器执行反向转换。
- Is there a generally expected good coding practice that suggests a maximum length for an if-elif-else statements to ensure ease of following the code?
不是这样的。
编写清晰的代码,不要重复自己。
- Is there a threshold for the length of the array or the number of iterations where one of them performs better than the other?
没有特别的。性能有很多因素,但很少有明确的规则。
一般来说,首先让它工作,然后,如果有必要,让它更快。
关于python - 什么时候值得在 if-else 语句上使用循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75024328/