Python:优化此循环

时间:2010-10-23 02:21:29

标签: python for-loop

a = [(1,2),(3,1),(4,4),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5)]
# Quite a lot tuples in the list, 6 digits~
# I want to split it into rows and columns.
rows = 5
cols = 5

Data structure is
rows and cols are the index for the bit list
[rows, cols, (data)]

我使用循环来执行此操作,但处理大量元组需要很长时间。

processed_data = []
index = 0
for h in range(0, rows - 1):
    for w in range(0, cols - 1):
        li = []
        li = [h, w, a[index]]
        processed_data.append(li)
        index += 1

此操作耗时太长,有没有办法进行优化?非常感谢!

3 个答案:

答案 0 :(得分:2)

我根本不清楚你想要什么,但是这里以更优化的方式拍摄同一个循环:

import itertools as it

index = it.count(0) 
processed_data = [[h, w, a[next(index)]] 
                 for h in xrange(0, rows - 1)
                 for w in xrange(0, cols - 1)]

或者,因为您已经导入了itertools,

index = ite.count(0)
indices = it.product(xrange(0, rows-1), xrange(0, cols-1))
processed_data = [[h, w, a[next(index)]] for h, w in indices]

这些更快的原因是它们使用列表推导而不是for循环。列表推导有自己的操作码LIST_APPEND,它直接路由到正在构造的列表上的append方法。在正常的for循环中,虚拟机必须经历在列表对象上查找append方法的整个过程,这种方法相当昂贵。

此外,itertools是用C实现的,所以如果同一算法的速度不快,那么itertools就会出现错误。

答案 1 :(得分:2)

好吧,如果你真的想要指数那么糟糕......

[divmod(i, cols) + (x,) for i, x in itertools.izip(itertools.count(), a)]

答案 2 :(得分:0)

相关问题