Skip to main content
 首页 » 编程设计

python之比 if-elif 语句更快

2025年05月04日20emanlee

我从传感器实时接收大量点数。但是,我只需要 4 类点,即 top_left、top_right、bottom_left 和 bottom_right。我在 Python 2 中有一个 if-elif 语句,如下所示:

from random import random, randint 
 
# points below are received from sensor. however,  
# here in this post I am creating it randomly. 
points = [Point(randint(0, i), random(), random(), random()) for i in range(100)]  
 
# 4 categories 
top_left, top_right, bottom_left, bottom_right = None, None, None, None 
for p in points: 
    if p.id == 5: 
        top_left = p 
    elif p.id == 7: 
        top_right = p 
    elif p.id == 13: 
        bottom_left = p 
    elif p.id == 15: 
        bottom_right = p 
 
print top_left.id, top_left.x, top_left.y, top_left.z # check variable 

每个点都有一个 id 和 x, y, z 参数。这是一个内置类。我只是在这里展示一个示例类。

class Point(): 
    def __init__(self, id, x, y, z): 
        self.id = id 
        self.x = x 
        self.y = y 
        self.z = z 

是否有任何有效的方法来考虑实现相同的运行时间。

答案: 我正在添加从答案中得到的结果。似乎the answer by Elis Byberi是最快的。下面是我的测试代码:

class Point(): 
    def __init__(self, id, x, y, z): 
        self.id = id 
        self.x = x 
        self.y = y 
        self.z = z 
 
from random import random, randint 
n = 1000 
points = [Point(randint(0, i), random(), random(), random()) for i in range(n)] 
 
def method1(): 
    top_left, top_right, bottom_left, bottom_right = None, None, None, None 
    for p in points: 
        if p.id == 5: 
            top_left = p 
        elif p.id == 7: 
            top_right = p 
        elif p.id == 13: 
            bottom_left = p 
        elif p.id == 15: 
            bottom_right = p 
    #print top_left.id, top_left.x, top_left.y, top_left.z 
 
def method2(): 
    categories = { 
        5: None,  # top_left 
        7: None,  # top_right 
        13: None,  # bottom_left 
        15: None  # bottom_right 
    } 
 
    for p in points: 
        categories[p.id] = p 
 
    top_left = categories[5] 
    #print top_left.id, top_left.x, top_left.y, top_left.z 
 
def method3(): 
    name_to_id = {'top_left': 5, 'top_right': 7, 'bottom_left': 13, 'bottom_right': 15} 
    ids = [value for value in name_to_id.values()] 
    bbox = {id: None for id in ids} 
 
    for point in points: 
        try: 
            bbox[point.id] = Point(point.id, point.x, point.y, point.z) 
        except KeyError:  # Not an id of interest. 
            pass 
 
    top_left = bbox[name_to_id['top_left']] 
    #print top_left.id, top_left.x, top_left.y, top_left.z 
 
from timeit import Timer 
print 'method 1:', Timer(lambda: method1()).timeit(number=n) 
print 'method 2:', Timer(lambda: method2()).timeit(number=n) 
print 'method 3:', Timer(lambda: method3()).timeit(number=n) 

查看下面返回的输出:

ravi@home:~/Desktop$ python test.py  
method 1: 0.174991846085 
method 2: 0.0743980407715 
method 3: 0.582262039185 

请您参考如下方法:

您可以使用字典来保存对象。 Dict 在键查找方面非常高效。

使用 dict 的速度是使用 if else block 的两倍。

这是python中最高效的方式:

from random import random, randint 
 
class Point(): 
    def __init__(self, id, x, y, z): 
        self.id = id 
        self.x = x 
        self.y = y 
        self.z = z 
 
# points below are received from sensor. however, 
# here in this post I am creating it randomly. 
points = [Point(randint(0, i), random(), random(), random()) for i in 
          range(100)] 
 
# 4 categories 
categories = { 
    5: None,  # top_left 
    7: None,  # top_right 
    13: None,  # bottom_left 
    15: None  # bottom_right 
} 
 
for p in points: 
    categories[p.id] = p 
 
>>> print categories[5].id, categories[5].x, categories[5].y, categories[5].z  # check variable 
5 0.516239541892 0.935096344266 0.0859987803457