Python:有效地迭代多维列表

Sat*_*vik 2 python loops multidimensional-array

我正在使用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
Run Code Online (Sandbox Code Playgroud)

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

Amb*_*ber 5

并不是的.在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
Run Code Online (Sandbox Code Playgroud)

  • 对 :).此外,也许您可​​以将if条件缩短为:`0 <= i <lH且0 <= j <lW且lpic [i] [j] =="0"`. (2认同)

wer*_*dle 5

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

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

  2. 在参数中使用min和以省略外循环中的“if”。所以你的代码看起来像这样:maxxrange

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
Run Code Online (Sandbox Code Playgroud)

这将略微提高性能。