我需要一种方法,在类似矩阵结构中的每一行的下降索引位置附加或插入/
。我发生的事情是我有一个程序,它接受列表的起始值和长度^ 2然后从这些值创建列表I.E。:
answer(17, 4) = [17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
然后我将其转换为矩阵或嵌套列表:
matrix = [id_arr[i:i + length] for i in range(0, len(id_arr), length)]
输出:[[17, 18, 19, 20], [21, 22, 23, 24], [25, 26, 27, 28], [29, 30, 31, 32]]
[17, 18, 19, 20] # matrix[0]
[21, 22, 23, 24] # matrix[1]
[25, 26, 27, 28] # matrix[2]
[29, 30, 31, 32] # matrix[3]
现在我想要一种方法在矩阵的每一行的下降索引位置插入或附加/
.E:
17 18 19 20 /
21 22 23 / 24
25 26 / 27 28
29 / 30 31 32
完整代码:
def answer(start, length):
# Generate the list of given start value and length
id_arr = list(range(start, start + length ** 2))
# Create a matrix of the list
matrix = [id_arr[i:i + length] for i in range(0, len(id_arr), length)]
# Attempt to try and insert the /
for row in matrix:
row.insert(len(matrix), '/')
print row
print len(matrix)
answer(17, 4)
输出:
[17, 18, 19, 20, '/']
[21, 22, 23, 24, '/']
[25, 26, 27, 28, '/']
[29, 30, 31, 32, '/']
正如您所看到的,我当前的代码只会在每行的末尾附加/
。
答案 0 :(得分:3)
使用枚举并获取每一行的索引并插入/每行的长度减去索引
def answer(start, length):
# Generate the list of given start value and length
id_arr = list(range(start, start + length ** 2))
# Create a matrix of the list
matrix = [id_arr[i:i + length] for i in range(0, len(id_arr), length)]
# Attempt to try and insert the /
for i,row in enumerate(matrix):
row.insert(len(matrix)-i, '/')
print row
print len(matrix)
answer(17, 4)
输出:
[17, 18, 19, 20, '/']
[21, 22, 23, '/', 24]
[25, 26, '/', 27, 28]
[29, '/', 30, 31, 32]
4
答案 1 :(得分:0)
您应该减少插入/
def answer(start, length):
# Generate the list of given start value and length
id_arr = list(range(start, start + length ** 2))
# Create a matrix of the list
matrix = [id_arr[i:i + length] for i in range(0, len(id_arr), length)]
# Attempt to try and insert the /
l = len(matrix)
for row in matrix:
row.insert(l, '/')
l -= 1
print row
print len(matrix)
answer(17, 4)