python - 带有列表的字典 : Fastest way to get the key corresponding to the minimum value of the fourth list item?

标签 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]点(第四个元素)中列表项对应的键的最快方法是什么?

最佳答案

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

This article Guido 也有类似的优化问题。要点是像 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

关于python - 带有列表的字典 : Fastest way to get the key corresponding to the minimum value of the fourth list item?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26264350/

相关文章:

python - 如何解决 Django 中的 "TypeError at/post/new/"

vb.net - 如何在下拉列表中按字母顺序对值进行排序? VB.net

python - 迭代嵌套的 Python 字典

python - 哪个模块应该包含 logging.config.dictConfig(my_dictionary)?我的字典呢?

python - 使用数据透视 reshape pandas 数据框并提供多列作为索引

python - 类型错误 : Unrecognized keyword arguments: {'show_accuracy' : True} #yelp challenge dataset

Python - 我的网络应用程序不断显示 "Hello World!"

algorithm - 为什么选择排序的下限只考虑 n/2 次迭代?

java - 韩文字符的排序和分组(不熟悉韩文)

c++ - map的反向迭代,通过getter访问/无拷贝