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
并不一定比使用for循环快,实际上可能会慢一些。你知道吗Guido的This article有一个类似的优化问题。它的优点是像
min
和map
这样的函数可以在C中使用循环而不是Python循环,但是它们必须进行更多的函数查找。结果表明,Python的循环开销小于Python的函数查找开销,因此循环版本通常会更快。用圭多的话说:一些时间安排:
相关问题 更多 >
编程相关推荐