python数据分析建模每日一题(5月2日)——顺时针逆时针打印矩阵


#顺时针打印
list1 = [[2,3,4,5],[5,6,7,8],[3,4,5,9],[10,11,23,45],[1,4,7,2]]
left = 0 #列起始
top = 0 #行起始
right = len(list1[0]) #-1为列结束
bottom  = len(list1) #-1为行结束
print ('first')
result = []
while(left <= right and top<= bottom):
    
    #打印上边的行,行号是top,列范围是[left,right-1]
    for i in range(left,right - 1):
        result.append(list1[top][i])
    #打印右边的列,列号right-1,行范围是[top,bottom -1]
    for i in range(top,bottom -1):
        result.append(list1[i][right - 1])
    #打印下边的行,行号是bottom,列范围是[right-1,left]  
    for i in range(right-1,left,-1):
        result.append(list1[bottom -1][i])
    #打印左边的列,列号left,行范围是[bottom -1,top-1]   
    for i in range(bottom -1,top,-1):
        result.append(list1[i][left])     
    left += 1
    top += 1
    right -= 1
    bottom -= 1
print (result)


#逆时针打印
list1 = [[2,3,4,5],[5,6,7,8],[3,4,5,9],[10,11,23,45],[1,4,7,2]]
left = 0
top = 0
right = len(list1[0])
bottom  = len(list1)
result2 = []
print ('second')
while(left <= right and top<= bottom):
    #打印左边的列,列号left,行范围是[top,bottom -1]
    for i in range(top,bottom - 1):
        result2.append(list1[i][left])
    #打印下边的行,行号是bottom,列范围是[left,right -1]  
    for i in range(left,right -1):
        result2.append(list1[bottom-1][i])
    #打印右边的列,列号right-1,行范围是[bottom -1,top-1]
    for i in range(bottom -1,top,-1):
        result2.append(list1[i][right-1])
    #打印上边的行,行号是top,列范围是[left,right-1]
    for i in range(right - 1,left,-1):
        result2.append(list1[top][i])  
    left += 1
    top += 1
    right -= 1
    bottom -= 1
print(result2)
#注意 range永远不包含右边括号的值


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值