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永远不包含右边括号的值


猜你喜欢

转载自blog.csdn.net/u013344884/article/details/80169309