Skip to main content
 首页 » 编程设计

python之Python 中的对角线网格遍历

2025年05月04日14EasonJim

为清晰起见进行了编辑

我到处搜索这个,但没有找到任何东西。我想遍历一个 2D 字符串列表并像这里那样显示切片 Traverse 2D Array (Matrix) Diagonally 但在 python 中。

lines = ['xmfycxvc', 
         'caubmekv', 
         'awactivb', 
         'paphzkcn', 
         'sbsaakjy', 
         'tsewlhvk'] 
diagonals = [] 
i = 0 
while i < len(lines): 
   j = 0 
   diagonal = '' 
   while j < len(lines[0]): 
      diagonal += lines[j][j] 
      i += 1 
diagonals.append(diagonal) 
print(diagonals) 

我知道我的索引是错误的,但我已经尝试了所有方法,但仍然无法使它像链接一样。我最接近的是拥有每个对角线,但也会像这样的球体环绕矩阵 ['xaahah','muczkv','fbtkjk','cevnss','xkbpbs','vvaasw ','xxwpal'] 但我不想这样。

我想对角线遍历字符串矩阵并打印对角线,例如['x','cm','aaf','pwuy','saabc','tbpcmx','sshtev','eazikc','wakvv','lkcb','hjn','vy ','k'] 及其对应部分从左上角 -> 右下角。

请您参考如下方法:

通过一些推理,我们得到矩阵中每条对角线的列号(或下文中的 x)和行号(y ) 是常数。我们可以使用一个 collections.defaultdict 作为我们的数据结构,它被自动初始化为一个空列表,并在所有矩阵元素上有一个循环,找到每个元素所属的对角线,并在我们的 默认字典。

def getdiags(matrix, nr, nc): 
    from collections import defaultdict 
    d = defaultdict(list) 
    for y in range(nr): 
        for x in range(nc): 
            d[x-y].append(matrix[y][x]) 
    return d 

我们也可以利用效用函数按顺序呈现我们的结果

def printdiags(diags): 
    for i in sorted(diags): 
        print diags[i] 

最后我们在 IPython 中测试我们的东西

In [1]: def getdiags(matrix, nr, nc): 
        from collections import defaultdict 
        d = defaultdict(list) 
        for y in range(nr): 
                for x in range(nc): 
                        d[x-y].append(matrix[y][x]) 
        return d 
   ...:      
 
In [2]: def printdiags(diags): 
        for i in sorted(diags): 
                print diags[i] 
   ...:          
 
In [3]: from pprint import pprint 
 
In [4]: m = [["%3.3d"%(r*100+c)  for c in range(5)] for r in range(4)] 
 
In [5]: pprint(m) 
[['000', '001', '002', '003', '004'], 
 ['100', '101', '102', '103', '104'], 
 ['200', '201', '202', '203', '204'], 
 ['300', '301', '302', '303', '304']] 
 
In [6]: diags = getdiags(m, 4, 5) 
 
In [7]: printdiags(diags) 
['300'] 
['200', '301'] 
['100', '201', '302'] 
['000', '101', '202', '303'] 
['001', '102', '203', '304'] 
['002', '103', '204'] 
['003', '104'] 
['004'] 
 
In [8]:  

就这样

附录

在后期的编辑中,OP 表示他们的输入是一个等长字符串列表,并且根据对角线列表寻找答案。

我上面的 getdiags 也适用于新的替代数据结构,并且获取搜索列表非常简单:

def listofdiags(diags): 
    return [''.join(diags[i]) for i in sorted(diags)] 

当然,这种转换也可以在 内部 getdiagonals 中实现,但这留作练习。

看,没有defaultdict

# List of Strings from Diagonals 
def lsd(m, nr, nc): 
    res = ["" for i in range(nr+nc-1)] 
    for r in range(nr): 
        for c in range(nc): 
            i = c-r+nr-1 
            res[i] = res[i]+m[r][c] 
    return res 
 
pprint(lsd(m, 4, 5)) 
# ['300', 
#  '200301', 
#  '100201302', 
#  '000101202303', 
#  '001102203304', 
#  '002103204', 
#  '003104', 
#  '004'] 

yield解决方案

以下效率较低,但为了完整起见,这里是:

def enumdiags(m, nr, nc): 
    for i in range(nr+nc-1): 
        s = "" 
        for r in range(nr): 
            for c in range(nc): 
                if c-r+nr-1 == i : s = s+m[r][c] 
        yield i, s 
 
for i, s in enumdiags(m, 4, 5): 
    print i, s 
# 0 300 
# 1 200301 
# 2 100201302 
# 3 000101202303 
# 4 001102203304 
# 5 002103204 
# 6 003104 
# 7 004