Python实现循环打印举证对角线数据列表

菜鸟方法,不喜勿喷,欢迎指正

测试矩阵:

# 测试矩阵
_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],
]
  1. 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]

  1. 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]
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值