【问题标题】:Python: Efficiently iterating over a multidimensional listPython:有效地迭代多维列表
【发布时间】:2012-01-05 20:26:37
【问题描述】:

我正在使用 for 循环遍历二维列表:

def itr(lpic, lH, lW, x, y):
    '''lpic=2D-Array; lH=Row_count; lW=Column_count;'''
    stack = []
    range_x = range(x-1, x+2)
    range_y = range(y-1, y+2)
    append = stack.append
    for i in range_x:
                if 0<=i<lH:#i is a valid index *Updated
                    for j in range_y:
                        if (0<=j<lW) and (lpic[i][j]=="0"):
                            lpic[i][j] = "1"
                            append([i, j])
    return stack

我想知道是否有更好的方法来用 Python2.5 做同样的事情。

【问题讨论】:

    标签: python loops multidimensional-array


    【解决方案1】:

    您的代码有两个简单的优化:

    1. 使用xrange 代替range。这将阻止生成两个临时列表。

    2. xrange 的参数中使用minmax 以在外循环中省略'if'。所以你的代码看起来像这样:

    def itr(lpic, lH, lW, x, y):
        '''lpic=2D-Array; lH=Row_count; lW=Column_count;'''
        stack = []
        range_x = xrange(max(0,x-1), min(lH,x+2))
        range_y = xrange(max(0,y-1), min(lW,y+2))
        append = stack.append
        for i in range_x:
          for j in range_y:
              if lpic[i][j]=="0":
                  lpic[i][j] = "1"
                  append([i, j])
        return stack
    

    这将略微提高性能。

    【讨论】:

    • 我听说 xrange 在 Python3 中已被弃用。
    • @Sathvik: range 在 Python3 中的行为类似于 Python2 中的 xrangelist(range(...)) 是 Python2 中 range 的 Python3 等价物。因此,name xrange 已从 Python3 中删除,但行为未删除。
    【解决方案2】:

    不是。在 Python 2.6 中,如果您想稍微压缩代码,可以使用 itertools.product() 将其转换为单个 for 循环,但一般效率不会完全改变 - 你仍然有循环的N*M 迭代。

    import itertools
    
    def itr(lpic, lH, lW, x, y):
        '''lpic=2D-Array; lH=Row_count; lW=Column_count;'''
        stack = []
        range_x = range(x-1, x+2)
        range_y = range(y-1, y+2)
        append = stack.append
        for i,j in itertools.product(range_x, range_y):
            if 0 <= i < lh and 0 <= j < lW and lpic[i][j]=="0":
                lpic[i][j] = "1"
                append([i, j])
        return stack
    

    【讨论】:

    • itertools.product 在 2.6+ 中。
    • @Avaris - 是的。 :) 那么,第一句话就成立了。 :)
    • 对 :)。另外,也许您可​​以将 if 条件缩短为:0&lt;=i&lt;lH and 0&lt;=j&lt;lW and lpic[i][j]=="0"
    猜你喜欢
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 2012-05-12
    • 2013-05-09
    • 2021-08-12
    • 1970-01-01
    • 2021-02-18
    • 2012-04-29
    相关资源
    最近更新 更多