简体   繁体   English

python中的最佳方法是什么:if语句中的OR或IN?

[英]What is the best approach in python: multiple OR or IN in if statement?

What is the best approach in python: multiple OR or IN in if statement? python中的最佳方法是什么:if语句中的ORIN Considering performance and best pratices. 考虑性能和最佳实践。

if cond == '1' or cond == '2' or cond == '3' or cond == '4' (etc...) :

OR 要么

if cond in ['1','2','3','4']:

Thank you. 谢谢。

The best approach is to use a set : 最好的方法是使用set

if cond in {'1','2','3','4'}:

as membership testing in a set is O(1) (constant cost). 因为集合中的成员资格测试为O(1)(不变成本)。

The other two approaches are equal in complexity; 其他两种方法的复杂度是相同的。 merely a difference in constant costs. 只是固定成本的差异。 Both the in test on a list and the or chain short-circuit; 列表in待测和链or链短路; terminate as soon as a match is found. 找到匹配项后立即终止。 One uses a sequence of byte-code jumps (jump to the end if True ), the other uses a C-loop and an early exit if the value matches. 一种使用字节码跳转序列(如果为True则跳转到末尾),另一种使用C循环,如果值匹配则使用提前退出。 In the worst-case scenario, where cond does not match an element in the sequence either approach has to check all elements before it can return False . 在最坏的情况下,如果cond与序列中的元素匹配,则两种方法都必须先检查所有元素,然后才能返回False Of the two, I'd pick the in test any day because it is far more readable. 在这两者之中,我每天都会选择in测试,因为它更具可读性。

Pieters answer is the best in most cases. 彼得的回答在大多数情况下是最好的。 However, in your specific case, I wouldn't use in or or but instead do this: 但是,在您的特定情况下,我不会inor使用in而是这样做:

if 0 < int(cond) < 5:

If cond is '1', '2', '3', or '4', the if block will run. 如果cond为'1','2','3'或'4',则if块将运行。 Nice thing about this is that it is shorter than the other answers. 这样做的好处是,它比其他答案要短。

This actually depends on the version of Python. 这实际上取决于Python的版本。 In Python 2.7 there were no set constants in the bytecode, thus in Python 2 in the case of a fixed constant small set of values use a tuple: Python 2.7中,字节码中没有设置常量,因此在Python 2中,如果使用固定常量,则较小的一组值将使用元组:

if x in ('2', '3', '5', '7'):
    ...

A tuple is a constant: 元组是一个常数:

>>> dis.dis(lambda: item in ('1','2','3','4'))
  1           0 LOAD_GLOBAL              0 (item)
              3 LOAD_CONST               5 (('1', '2', '3', '4'))
              6 COMPARE_OP               6 (in)
              9 RETURN_VALUE

Python is also smart enough to optimize a constant list on Python 2.7 to a tuple: Python也足够聪明,可以将Python 2.7上的常量列表优化为元组:

>>> dis.dis(lambda: item in ['1','2','3','4'])
  1           0 LOAD_GLOBAL              0 (item)
              3 LOAD_CONST               5 (('1', '2', '3', '4'))
              6 COMPARE_OP               6 (in)
              9 RETURN_VALUE        

But Python 2.7 bytecode (and compiler) lacks support for constant sets: 但是Python 2.7字节码(和编译器)缺乏对常量集的支持:

>>> dis.dis(lambda: item in {'1','2','3','4'})
  1           0 LOAD_GLOBAL              0 (item)
              3 LOAD_CONST               1 ('1')
              6 LOAD_CONST               2 ('2')
              9 LOAD_CONST               3 ('3')
             12 LOAD_CONST               4 ('4')
             15 BUILD_SET                4
             18 COMPARE_OP               6 (in)
             21 RETURN_VALUE        

Which means that the set in if condition needs to be rebuilt for each test . 这意味着需要为每个测试重建if条件。


However in Python 3.4 the bytecode supports set constants; 但是在Python 3.4中 ,字节码支持设置常量。 there the code evaluates to: 代码在那里评估为:

>>> dis.dis(lambda: item in {'1','2','3','4'})
  1           0 LOAD_GLOBAL              0 (item)
              3 LOAD_CONST               5 (frozenset({'4', '2', '1', '3'}))
              6 COMPARE_OP               6 (in)
              9 RETURN_VALUE

As for the multi- or code, it produces totally hideous bytecode: 至于多重or代码,它会产生完全可怕的字节码:

>>> dis.dis(lambda: item == '1' or item == '2' or item == '3' or item == '4')
  1           0 LOAD_GLOBAL              0 (item)
              3 LOAD_CONST               1 ('1')
              6 COMPARE_OP               2 (==)
              9 JUMP_IF_TRUE_OR_POP     45
             12 LOAD_GLOBAL              0 (item)
             15 LOAD_CONST               2 ('2')
             18 COMPARE_OP               2 (==)
             21 JUMP_IF_TRUE_OR_POP     45
             24 LOAD_GLOBAL              0 (item)
             27 LOAD_CONST               3 ('3')
             30 COMPARE_OP               2 (==)
             33 JUMP_IF_TRUE_OR_POP     45
             36 LOAD_GLOBAL              0 (item)
             39 LOAD_CONST               4 ('4')
             42 COMPARE_OP               2 (==)
        >>   45 RETURN_VALUE        

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

相关问题 在 python 中测量多种语言文本之间相似性的最佳方法是什么? - What is the best approach to measure a similarity between texts in multiple languages in python? Python:扁平化字典列表的最佳方法是什么 - Python: What is Best Approach for Flattening a list of Dictionary 最好的 Python 字符串拆分方法是什么? - What's the best Python string split approach? Python 中多个 websocket 客户端连接的最佳方法? - Best approach to multiple websocket client connections in Python? 在同一全局python应用程序中的多个模块中使用SQLite3时,最佳方法是什么? - What is the best approach when using SQLite3 from multiple module in the same global python application? 从 pandas dataframe 中选择多个轴,最好的方法是什么? - Selecting multiple axes from a pandas dataframe, what is the best approach? 为人脸识别存储每个人的多个向量的最佳方法是什么 - What is the best approach for storing multiple vectors per person for face recognition 用python解析非有序HTML页面的最佳方法是什么? - What is the best approach to parse a non ordered HTML page with python? Elasticsearch 分页的最佳方法是什么? - What is the best approach for Elasticsearch pagination? 使用 python 解决这个问题的最佳方法 - Best approach to this question using python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM