代码之家  ›  专栏  ›  技术社区  ›  user469652

Python:优化这个循环

  •  0
  • user469652  · 技术社区  · 14 年前
    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 回复  |  直到 12 年前
        1
  •  2
  •   aaronasterling    14 年前

    我一点也不清楚你想要什么,但这里有一个以更优化的方式在同一个循环中拍摄的镜头:

    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)]
    

    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 对于 循环,虚拟机必须经历查找 追加

    另外,itertools是用C语言实现的,所以如果对同一算法来说速度不快,那么itertools中就有一个bug。

        2
  •  2
  •   Ignacio Vazquez-Abrams    14 年前

    好吧,如果你真的非常想要指数。。。

    [divmod(i, cols) + (x,) for i, x in itertools.izip(itertools.count(), a)]
    
        3
  •  0
  •   Community CDub    7 年前