gpt4 book ai didi

Python 最佳实践 : series of "or"s or "in"?

转载 作者:太空狗 更新时间:2023-10-30 02:41:14 25 4
gpt4 key购买 nike

我正在研究 project关于以下行的问题:

a == "EQUAL" or a == "NOT EQUAL" or a == "LESS" or a == "GREATER"

我提议进行更改以使其“更简单”,如下所示:

a in ["EQUAL", "NOT EQUAL", "LESS", "GREATER"]

什么被认为是最佳实践,什么最有利于性能?这适用于经常更新的用户界面代码,因此性能的微小改进可能会很明显。我知道如果发现第一个示例,第一个示例将“快速失败”,并且我假设第二个示例也会“快速失败”。

此外,使用像这样的字典会不会更快:

a in {"EQUAL", "NOT EQUAL", "LESS", "GREATER"}

...这样就不需要构建列表了?

PEP-8 唯一说的(我能找到的):

...code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code...

However, know when to be inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best.

最佳答案

我会选择套装。它更具可读性。 的字符串在某些情况下可能会更快,因为运算符短路并且每次都没有构建项目列表的开销,但我认为牺牲可读性是不值得的。这是一个快速而肮脏的基准。这是 Python 2.7

 def t1(x):
return (x == "Foo" or x == "Bar" or x == "Baz" or x == "Quux")


def t2(x):
return x in {"Foo", "Bar", "Baz", "Quux"}

[2.7.9]>>> import timeit
[2.7.9]>>> timeit.timeit(lambda : t1("Quux"))
0.22514700889587402
[2.7.9]>>> timeit.timeit(lambda : t1("Foo"))
0.18890380859375
[2.7.9]>>> timeit.timeit(lambda : t2("Quux"))
0.27969884872436523
[2.7.9]>>> timeit.timeit(lambda : t2("Foo"))
0.25904297828674316

Python 3 数字。

 [3.4.2]>>> timeit.timeit(lambda : t1("Quux"))
0.25126787397312
[3.4.2]>>> timeit.timeit(lambda : t1("Foo"))
0.1722603400121443
[3.4.2]>>> timeit.timeit(lambda : t2("Quux"))
0.18982669000979513
[3.4.2]>>> timeit.timeit(lambda : t2("Foo"))
0.17984321201220155

关于Python 最佳实践 : series of "or"s or "in"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39960941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com