如何在Python中调用用于匹配键的函数?

时间:2020-07-12 11:24:10

标签: python python-3.x function find key

results = try CoreData.stack.context.fetch(request) as? [[String:NSNumber]]

我认为如果状态为O(logN)则进行复数运算很复杂。 所以我以这种方式称呼函数拟合为键,因为我认为它的复杂度为O(1), 但这似乎很慢。人们说它很脏。

还有其他方法可以将随机函数匹配到其键或ID吗? 或通过其他方法更好地解决此问题。

1 个答案:

答案 0 :(得分:0)

除了感觉之外,您为什么认为从dict打电话很慢?真正了解最好(也许唯一)的方法是测量。

我运行了以下脚本:

def fin1():
    #some context
    pass

def fin2():
    #some context
    pass

def fin3():
    #some context
    pass

def fin4():
    #some context
    pass

test_dic = {"1": fin1, "2": fin2, "3": fin3, "4": fin4}

def indirect():
    some_string = "123123wafds" * 10000

    result_string = ""
    for single_str in some_string:
        if single_str in test_dic:
            test_dic[single_str]()
        else:
            result_string += single_str

def direct():
    some_string = "123123wafds" * 10000

    result_string = ""
    for single_str in some_string:
        if single_str == "1":
            fin1()
        elif single_str == "2":
            fin2()
        elif single_str == "3":
            fin3()
        elif single_str == "4":
            fin4()

        else:
            result_string += single_str

for i in range(1000):
    indirect()

for i in range(1000):
    direct()

我使用cProfile模块进行测量,如下所示:

$ python3 -m cProfile test_indirect.py 
         120002003 function calls in 33.458 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.001    0.001   33.458   33.458 test_indirect.py:1(<module>)
 40000000    1.941    0.000    1.941    0.000 test_indirect.py:1(fin1)
     1000   12.334    0.012   15.150    0.015 test_indirect.py:19(indirect)
     1000   15.360    0.015   18.307    0.018 test_indirect.py:29(direct)
 40000000    1.936    0.000    1.936    0.000 test_indirect.py:5(fin2)
 40000000    1.886    0.000    1.886    0.000 test_indirect.py:9(fin3)
        1    0.000    0.000   33.458   33.458 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

结果表明,间接(使用dict)比直接(使用if / elif)要快。因此,继续使用它。