Python:使用列表推导而不是循环来提高性能 [英] Python: using a List Comprehensions instead of loop in order to improve the performance
问题描述
我有字典中的类型(示例)
I have a type from a dictionary (example)
l =('1037_97',["a","b","c","d","e"])
我希望保存一个文件(las格式),但是 Liblas 只能写一个观点.
I wish to save a file (las format) but Liblas can write only single point.
for l in Groups.iteritems():
for p in xrange(len(l[1])):
file_out.write(l[1][p])
如果可能,我正在尝试使用 列表理解功能,以节省代码并加快循环速度
I am trying to use if it's possible a List Comprehensions in order to save code and speed the loop
推荐答案
如果您想使用更短的解决方案,请考虑将map()
用于内部循环,甚至两者都使用.但是,它不太可能获得显着的性能提升.但是,for p in l[1]:
仍可能比使用xrange
的构造更快.下面的示例应在一行中完成您想要的操作:
If you want a shorter solution, consider using map()
for inner cycle, or even for both. But it is unlikely to get a significant performance boost. However, for p in l[1]:
still may be faster than that construction with xrange
. The following example should do what you wanted in a single line:
map(lambda g: map(file_out.write, g), groups.itervalues())
现在让我们比较不同实现的性能.在这里,我尝试测量一些测试数据上的时间:
Now let's compare performance of different implementations. Here I tried to measure times on some test data:
import timeit
groups = dict(('1037_%d' % i, ["a","b","c","d","e"]) for i in xrange(100))
class FOut(object):
def write(self, v):
#print v
pass
file_out = FOut()
def using_map():
map(lambda g: map(file_out.write, g), groups.itervalues())
def initial_version():
for l in groups.iteritems():
for p in xrange(len(l[1])):
file_out.write(l[1][p])
def seq_iteration():
for l in groups.iteritems():
for p in l[1]:
file_out.write(p)
def seq_iteration_values():
for l in groups.itervalues():
for p in l:
file_out.write(p)
def list_compr():
[[file_out.write(v) for v in g] for g in groups.itervalues()]
tests = ('initial_version', 'using_map', 'seq_iteration', 'list_compr', 'seq_iteration_values')
for test in tests:
print test, timeit.timeit('%s()'%test, 'from __main__ import %s'%test, number=10000)
结果是:
initial_version 0.862531900406
using_map 0.703296899796
seq_iteration 0.541372060776
list_compr 0.632550954819
seq_iteration_values 0.493131160736
如您所见,您的初始版本是最慢的,修复迭代有很大帮助,map()
版本很短,但不及itervalues()
版本那么快.创建不需要的列表的列表理解还不错,但仍然比普通周期慢.
As you can see, your initial version is the slowest, fixing iteration helps a lot, map()
version is short, but not as fast as the version with itervalues()
. List comprehension that creates unneeded lists is not bad, but still slower than the plain cycle.
这篇关于Python:使用列表推导而不是循环来提高性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!