Bio*_*eek 44 python matrix diagonal
我正在寻找一种Pythonic方法来获取(方形)矩阵的所有对角线,表示为列表列表.
假设我有以下矩阵:
matrix = [[-2, 5, 3, 2],
[ 9, -6, 5, 1],
[ 3, 2, 7, 3],
[-1, 8, -4, 8]]
Run Code Online (Sandbox Code Playgroud)
然后大对角线很容易:
l = len(matrix[0])
print [matrix[i][i] for i in range(l)] # [-2, -6, 7, 8]
print [matrix[l-1-i][i] for i in range(l-1,-1,-1)] # [ 2, 5, 2, -1]
Run Code Online (Sandbox Code Playgroud)
但是我无法想出一种生成所有对角线的方法.我正在寻找的输出是:
[[-2], [9, 5], [3,-6, 3], [-1, 2, 5, 2], [8, 7, 1], [-4, 3], [8],
[2], [3,1], [5, 5, 3], [-2, -6, 7, 8], [9, 2, -4], [3, 8], [-1]]
Run Code Online (Sandbox Code Playgroud)
Mar*_*nen 50
可能有更好的方法在numpy比下面做,但我还不太熟悉它:
import numpy as np
matrix = np.array(
[[-2, 5, 3, 2],
[ 9, -6, 5, 1],
[ 3, 2, 7, 3],
[-1, 8, -4, 8]])
diags = [matrix[::-1,:].diagonal(i) for i in range(-3,4)]
diags.extend(matrix.diagonal(i) for i in range(3,-4,-1))
print [n.tolist() for n in diags]
Run Code Online (Sandbox Code Playgroud)
[[-2], [9, 5], [3, -6, 3], [-1, 2, 5, 2], [8, 7, 1], [-4, 3], [8], [2], [3, 1], [5, 5, 3], [-2, -6, 7, 8], [9, 2, -4], [3, 8], [-1]]
Run Code Online (Sandbox Code Playgroud)
编辑:更新以概括任何矩阵大小.
import numpy as np
# Alter dimensions as needed
x,y = 3,4
# create a default array of specified dimensions
a = np.arange(x*y).reshape(x,y)
print a
print
# a.diagonal returns the top-left-to-lower-right diagonal "i"
# according to this diagram:
#
# 0 1 2 3 4 ...
# -1 0 1 2 3
# -2 -1 0 1 2
# -3 -2 -1 0 1
# :
#
# You wanted lower-left-to-upper-right and upper-left-to-lower-right diagonals.
#
# The syntax a[slice,slice] returns a new array with elements from the sliced ranges,
# where "slice" is Python's [start[:stop[:step]] format.
# "::-1" returns the rows in reverse. ":" returns the columns as is,
# effectively vertically mirroring the original array so the wanted diagonals are
# lower-right-to-uppper-left.
#
# Then a list comprehension is used to collect all the diagonals. The range
# is -x+1 to y (exclusive of y), so for a matrix like the example above
# (x,y) = (4,5) = -3 to 4.
diags = [a[::-1,:].diagonal(i) for i in range(-a.shape[0]+1,a.shape[1])]
# Now back to the original array to get the upper-left-to-lower-right diagonals,
# starting from the right, so the range needed for shape (x,y) was y-1 to -x+1 descending.
diags.extend(a.diagonal(i) for i in range(a.shape[1]-1,-a.shape[0],-1))
# Another list comp to convert back to Python lists from numpy arrays,
# so it prints what you requested.
print [n.tolist() for n in diags]
Run Code Online (Sandbox Code Playgroud)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[0], [4, 1], [8, 5, 2], [9, 6, 3], [10, 7], [11], [3], [2, 7], [1, 6, 11], [0, 5, 10], [4, 9], [8]]
Run Code Online (Sandbox Code Playgroud)
Nem*_*emo 18
从向上和向右倾斜的对角线开始.
如果(x,y)是矩阵内的直角坐标,则需要变换为/从坐标方案(p,q)变换,其中p是对角线的数量,q是沿对角线的索引.(所以p = 0是[-2]对角线,p = 1是[9,5]对角线,p = 2是[3,-6,3]对角线,依此类推.)
要将(p,q)转换为(x,y),您可以使用:
x = q
y = p - q
Run Code Online (Sandbox Code Playgroud)
尝试插入p和q的值,看看它是如何工作的.
现在你只循环...对于p从0到2N-1,q从max(0,p-N + 1)到min(p,N-1).将p,q转换为x,y并打印.
然后对于其他对角线,重复循环但使用不同的转换:
x = N - 1 - q
y = p - q
Run Code Online (Sandbox Code Playgroud)
(这实际上只是左右翻转矩阵.)
对不起,我实际上并没有用Python编写代码.:-)
fla*_*kes 10
我首先制作简单的函数来复制任何矩形矩阵的行或列.
def get_rows(grid):
return [[c for c in r] for r in grid]
def get_cols(grid):
return zip(*grid)
Run Code Online (Sandbox Code Playgroud)
通过这两个函数,我可以通过在每行的开头/结尾添加一个递增/递减缓冲区来获得对角线.然后我获取此缓冲网格的列,然后删除每列上的缓冲区.即)
1 2 3 |X|X|1|2|3| | | |1|2|3|
4 5 6 => |X|4|5|6|X| => | |4|5|6| | => [[7],[4,8],[1,5,9],[2,6],[3]]
7 8 9 |7|8|9|X|X| |7|8|9| | |
Run Code Online (Sandbox Code Playgroud)
.
def get_backward_diagonals(grid):
b = [None] * (len(grid) - 1)
grid = [b[i:] + r + b[:i] for i, r in enumerate(get_rows(grid))]
return [[c for c in r if c is not None] for r in get_cols(grid)]
def get_forward_diagonals(grid):
b = [None] * (len(grid) - 1)
grid = [b[:i] + r + b[i:] for i, r in enumerate(get_rows(grid))]
return [[c for c in r if c is not None] for r in get_cols(grid)]
Run Code Online (Sandbox Code Playgroud)
我遇到了另一个有趣的解决方案.通过查看x和y的组合,可以立即发现行,列,前向和后向对角线.
Column = x Row = y F-Diag = x+y B-Diag = x-y B-Diag` = x-y-MIN
| 0 1 2 | 0 1 2 | 0 1 2 | 0 1 2 | 0 1 2
--|--------- --|--------- --|--------- --|--------- --|---------
0 | 0 1 2 0 | 0 0 0 0 | 0 1 2 0 | 0 1 2 0 | 2 3 4
1 | 0 1 2 1 | 1 1 1 1 | 1 2 3 1 |-1 0 1 1 | 1 2 3
2 | 0 1 2 2 | 2 2 2 2 | 2 3 4 2 |-2 -1 0 2 | 0 1 2
Run Code Online (Sandbox Code Playgroud)
从图中可以看出,每个对角线和轴都可以使用这些方程进行唯一识别.从每个表中获取每个唯一编号,并为该标识符创建容器.
请注意,向后对角线已偏移以从零索引处开始,并且向前对角线的长度始终等于向后对角线的长度.
test = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
max_col = len(test[0])
max_row = len(test)
cols = [[] for _ in range(max_col)]
rows = [[] for _ in range(max_row)]
fdiag = [[] for _ in range(max_row + max_col - 1)]
bdiag = [[] for _ in range(len(fdiag))]
min_bdiag = -max_row + 1
for x in range(max_col):
for y in range(max_row):
cols[x].append(test[y][x])
rows[y].append(test[y][x])
fdiag[x+y].append(test[y][x])
bdiag[x-y-min_bdiag].append(test[y][x])
print(cols)
print(rows)
print(fdiag)
print(bdiag)
Run Code Online (Sandbox Code Playgroud)
哪个会打印
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
[[1], [2, 4], [3, 5, 7], [6, 8, 10], [9, 11], [12]]
[[10], [7, 11], [4, 8, 12], [1, 5, 9], [2, 6], [3]]
Run Code Online (Sandbox Code Playgroud)
我最近重新发明了这个轮子。这是一个易于重用/扩展的方法,用于在方形列表列表中查找对角线:
def get_diagonals(grid, bltr = True):
dim = len(grid)
assert dim == len(grid[0])
return_grid = [[] for total in xrange(2 * len(grid) - 1)]
for row in xrange(len(grid)):
for col in xrange(len(grid[row])):
if bltr: return_grid[row + col].append(grid[col][row])
else: return_grid[col - row + (dim - 1)].append(grid[row][col])
return return_grid
Run Code Online (Sandbox Code Playgroud)
假设列表索引:
00 01 02 03
10 11 12 13
20 21 22 23
30 31 32 33
然后设置bltr = True
(默认),返回从左下角到右上角的对角线,即
00 # row + col == 0
10 01 # row + col == 1
20 11 02 # row + col == 2
30 21 12 03 # row + col == 3
31 22 13 # row + col == 4
32 23 # row + col == 5
33 # row + col == 6
Run Code Online (Sandbox Code Playgroud)
setting bltr = False
,返回从左下角到右上角的对角线,即
30 # (col - row) == -3
20 31 # (col - row) == -2
10 21 32 # (col - row) == -1
00 11 22 33 # (col - row) == 0
01 12 23 # (col - row) == +1
02 13 # (col - row) == +2
03 # (col - row) == +3
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
58076 次 |
最近记录: |