带列表的字典:最快的方法获得对应于第四个列表项最小值的键?

2024-03-28 11:56:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个应用程序,其中速度很重要。因此,我希望避免循环,并尽可能使用min。你知道吗

假设我有一本包含列表的词典:

test = {'test': ['test', 444, 2, 51, 1, 1],
        '222': ['222', 2222, 2, 9, 3, 4],
        '333': ['333', 2222, 6, 6, 5, 9]}

在[3]点(第四个元素)以字典中的最小值获取列表项的对应键的最快方法是什么?你知道吗


Tags: 方法test应用程序元素列表字典min速度
2条回答

注意,使用min并不一定比使用for循环快,实际上可能会慢一些。你知道吗

Guido的This article有一个类似的优化问题。它的优点是像minmap这样的函数可以在C中使用循环而不是Python循环,但是它们必须进行更多的函数查找。结果表明,Python的循环开销小于Python的函数查找开销,因此循环版本通常会更快。用圭多的话说:

Try to use map(), filter() or reduce() to replace an explicit for loop, but only if you can use a built-in function: map with a built-in function beats for loop, but a for loop with in-line code beats map with a lambda function!

一些时间安排:

test = {'test': ['test', 444, 2, 51, 1, 1],
        '222': ['222', 2222, 2, 9, 3, 4],
        '333': ['333', 2222, 6, 6, 5, 9]}

def using_for_loop():
    curr_min = 999
    for key, lst in test.items():
        val = lst[3]
        if val < curr_min:
            curr_key = key
            curr_min = val
    return curr_key

def using_min():  # From BrenBarn's answer
    return min(test, key=lambda k: test[k][3])

%timeit using_for_loop()
# 1000000 loops, best of 3: 724 ns per loop

%timeit using_min()
# 1000000 loops, best of 3: 1.35 µs per loop
min(test, key=lambda k: test[k][3])

相关问题 更多 >