#順時針打印
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永遠不包含右邊括號的值
python數據分析建模每日一題(5月2日)——順時針逆時針打印矩陣
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.