python - 如果与 Python 中的 Elif 相比,哪个更好?

标签 python python-3.x if-statement

我正在阅读 Grokking Algorithms,这似乎是一本强烈推荐的书。我正在查看“二进制搜索”的第一个算法,这个人使用两个“ifs”而不是“if”和“elif”。使用两个“如果”会更好还是更快?

def binary_search(list, item):
    low = 0
    high = len(list) - 1

    while low <= high:
        mid = (low + high)
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None

my_list = [1,3,5,7,9]

最佳答案

示例 1

>>> def foo():
    a = 10
    if a == 10:
        print("condition1")
    elif a == 10:
        print("condition2")
    else:
        print(0)    
>>> foo()
condition1
>>> 

elif 保证在 if 为真时不运行。

例子2

def foo():
    a = 10
    if a == 10:
        print("condition1")
    if a == 10:
        print("condition2")
    else:
        print(0)
>>> foo()
condition1
condition2
>>> 

示例 3 修改example2的if语句。

if a == 10:
    print("condition1")
    return a

输出

>>> foo()
condition1
10

因此,在您的情况下,在第一个 if 语句中添加一个 return 具有与 if-elif block 类似的操作。 (return a) 阻止在示例 3 中执行第二个 if 语句。

关于python - 如果与 Python 中的 Elif 相比,哪个更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61758941/

相关文章:

python风格: list of strings vs string. split()

python - (discord.py) 如何让我的机器人随机回复 DM?

python-3.x - Visual Studio Python "Failed to launch the Python Process, please validate the path ' python'' & 错误 : spawn python ENOENT

python - 谷歌CP : Creating Client() object locally

python - 从矩阵中减去转置但保留原始对角线

python - 通过启动命名空间 war 来替换 lxml StringElement 的内容?

python - 为什么 v*v 在 python 中比 v**2 快

python - 如何在一行中编写一个for循环和多个if语句?

mysql - Crystal Report 记录过滤 每个记录有 3 种不同的方式 CR10

java - 单行 If 语句在尝试在 If block 内声明变量时给出编译错误。是什么原因?