如何使用 python/sage 创建显示矩阵中列条目计数的行?

How to create a row that displays the counts of column entries in a matrix using python/sage?

这是我的矩阵:

A = matrix([[1,1,2,2,2], 
            [3,1,4,3,3], 
            [0,4,2,4,0], 
            [0,0,2,0,0], 
            [0,0,2,0,0]])

我想插入一个显示列条目数的 0 行。

这是我的原始代码:

A = matrix([[1,1,2,2,2],
            [3,1,4,3,3],
            [0,4,2,4,0],
            [0,0,2,0,0],
            [0,0,2,0,0]])
puzzle = A.insert_row(0, sum(A))

这段代码的错误在于它给出了每列的总和,而我只需要每列的计数。

我有什么

[ 4  6 12  9  5]
[ 1  1  2  2  2]
[ 3  1  4  3  3]
[ 0  4  2  4  0]
[ 0  0  2  0  0]
[ 0  0  2  0  0]

想要

[ 2  3  5  3  2]
[ 1  1  2  2  2]
[ 3  1  4  3  3]
[ 0  4  2  4  0]
[ 0  0  2  0  0]
[ 0  0  2  0  0]

最佳,

大卫

尝试nonzero_positions_in_column方法:

sage: A = matrix([[1,1,2,2,2], 
....:             [3,1,4,3,3], 
....:             [0,4,2,4,0], 
....:             [0,0,2,0,0], 
....:             [0,0,2,0,0]])
sage: A.column(1)
(1, 1, 4, 0, 0)
sage: A.nonzero_positions_in_column(1)
[0, 1, 2]

sage: v = vector([len(A.nonzero_positions_in_column(i)) for i in range(A.ncols())])
sage: A.insert_row(0, v)
[2 3 5 3 2]
[1 1 2 2 2]
[3 1 4 3 3]
[0 4 2 4 0]
[0 0 2 0 0]
[0 0 2 0 0]