我正在编写一个速度很重要的应用程序。因此,我想避免循环并尽可能使用 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 也有类似的优化问题。要点是像 min
和 map
这样的函数可以使用 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/