菜鸟方法,不喜勿喷,欢迎指正
测试矩阵:
# 测试矩阵
_list = [
[ 1, 2, 3, 4, 5, 6],
[ 7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18],
[19, 20, 21, 22, 23, 24],
[25, 26, 27, 28, 29, 30],
[31, 32, 33, 34, 35, 36],
]
- left -> right
# left -> right
x, y = 0, len(_list) - 1
left_to_right_list = []
for i in range(len(_list) * 2 - 1):
if (x == 0 and y == len(_list) - 1) or (x == len(_list) - 1 and y == 0):
left_to_right_list.append([_list[x][y]])
else:
temp_list = []
if i <= len(_list) - 1:
temp_y = y
temp_x = x
while temp_y <= len(_list) - 1:
temp_list.append(_list[temp_x][temp_y])
temp_x += 1
temp_y += 1
left_to_right_list.append(temp_list)
else:
x += 1 # 从第二行开始
y = 0 # 从第一列开始
temp_x = x
temp_y = y
while temp_x <= len(_list) - 1:
temp_list.append(_list[temp_x][temp_y])
temp_x += 1
temp_y += 1
left_to_right_list.append(temp_list)
y -= 1
for i in left_to_right_list:
print(i)
## 结果 ##
# [6]
# [5, 12]
# [4, 11, 18]
# [3, 10, 17, 24]
# [2, 9, 16, 23, 30]
# [1, 8, 15, 22, 29, 36]
# [7, 14, 21, 28, 35]
# [13, 20, 27, 34]
# [19, 26, 33]
# [25, 32]
# [31]
- right -> left
# right -> left
x, y = 0, 0
right_to_left_list = []
for i in range(len(_list) * 2 - 1):
if x == y:
right_to_left_list.append([_list[x][y]])
y += 1
else:
temp_list = []
if i <= len(_list) - 1:
# i小于等于列表长度时x为0
temp_y = i
temp_x = x
while temp_y >= 0:
temp_list.append(_list[temp_x][temp_y])
temp_x += 1
temp_y -= 1
right_to_left_list.append(temp_list)
y += 1
else:
x += 1
# i大于列表长度时y为列表长度
temp_y = len(_list) - 1
temp_x = x # 从第二行开始
while temp_x <= len(_list) - 1:
temp_list.append(_list[temp_x][temp_y])
temp_x += 1
temp_y -= 1
right_to_left_list.append(temp_list)
for i in right_to_left_list:
print(i)
## 结果 ##
# [1]
# [2, 7]
# [3, 8, 13]
# [4, 9, 14, 19]
# [5, 10, 15, 20, 25]
# [6, 11, 16, 21, 26, 31]
# [12, 17, 22, 27, 32]
# [18, 23, 28, 33]
# [24, 29, 34]
# [30, 35]
# [36]