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

时间:2014-10-08 18:55:30

标签: python sorting dictionary

我正在编写速度很重要的应用。因此,我想避免循环并尽可能使用min

说我有一个包含列表的字典:

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

使用字典中的最小值获取[3]点(第四个元素)中列表项的相应键的最快方法是什么?

2 个答案:

答案 0 :(得分:2)

请注意,使用min并不一定比使用for循环更快,实际上可能会更慢。

Guido的

This article有类似的优化问题。需要注意的是,像minmap这样的函数可以在C而不是Python循环中使用循环,但它们必须执行更多的函数查找。事实证明,Python的循环开销小于Python的函数查找开销,因此循环版本通常会更快。用圭多的话说:

  

尝试使用map(),filter()或reduce()来替换显式的for循环,但前提是你可以使用内置函数:map with a built-function beats for loop,but a for带有内联代码的循环使用lambda函数击败地图!

一些时间:

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

答案 1 :(得分:1)

min(test, key=lambda k: test[k][3])