认为这通常可以解决问题
输入
mats = array([[[0, 1, 2, 3, 4, 5],
[1, 0, 3, 4, 5, 6],
[2, 3, 0, 5, 6, 7],
[3, 4, 5, 0, 7, 8],
[4, 5, 6, 7, 0, 9],
[5, 6, 7, 8, 9, 0]],
[[0, 1, 2, 3, 4, 5],
[1, 0, 3, 4, 5, 6],
[2, 3, 0, 5, 6, 7],
[3, 4, 5, 0, 7, 8],
[4, 5, 6, 7, 0, 9],
[5, 6, 7, 8, 9, 0]]])
代码
# Recursively makes pyramiding column and row headers
def make_head(n):
pre = ''
if n/26:
pre = make_head(n/26-1)
alph = "abcdefghijklmnopqrstuvwxyz"
pre+= alph[n%26]
return pre
# Generator object to create header items for n-rows or n-cols
def gen_header(nitems):
n = -1
while n<nitems:
n+=1
yield make_head(n)
# Convert numpy to list
lmats = mats.tolist()
# Loop through each "matrix"
for mat in lmats:
# Pre store number of columns as we modify it before working rows
ncols = len(mat[0])
# add header value to front of each row from generator object
for row,hd in zip(mat,gen_header(len(mat))):
row.insert(0,hd)
# Create a "header" line for all the columns
col_hd = [hd for hd in gen_header(ncols-1)]
col_hd.insert(0,"A")
# Insert header line into lead row of matrix
mat.insert(0,col_hd)
# Convert back to numpy
mats = numpy.array(lmats)
输出(存储在垫子中的值):
array([[['A', 'a', 'b', 'c', 'd', 'e', 'f'],
['a', '0', '1', '2', '3', '4', '5'],
['b', '1', '0', '3', '4', '5', '6'],
['c', '2', '3', '0', '5', '6', '7'],
['d', '3', '4', '5', '0', '7', '8'],
['e', '4', '5', '6', '7', '0', '9'],
['f', '5', '6', '7', '8', '9', '0']],
[['A', 'a', 'b', 'c', 'd', 'e', 'f'],
['a', '0', '1', '2', '3', '4', '5'],
['b', '1', '0', '3', '4', '5', '6'],
['c', '2', '3', '0', '5', '6', '7'],
['d', '3', '4', '5', '0', '7', '8'],
['e', '4', '5', '6', '7', '0', '9'],
['f', '5', '6', '7', '8', '9', '0']]],
dtype='|S4')