[英]How to loop through a 2D list diagonally in python?
如果我有一個 function val) 然后我還需要檢查里面有沒有字母
iagonally)
如果您的 2D 列表保證是方形的,那么您可以按如下方式進行對角線檢查
def diagnoal_check(board2d, start_row, start_column, goal_row, goal_column, row_increment, column_increment):
curr_row = start_row
curr_column = start_column
while(curr_column < len(board2d) and curr_row < len(board2d) and curr_row >= 0 and curr_column >= 0):
if(board2d[curr_row][curr_column] == "P"):
return False
if(curr_column == goal_column and curr_row == goal_row):
return True
curr_column += column_increment
curr_row += row_increment
return False
然后更新您的條件代碼如下
x = False
if (abs(currow - newrow) == abs(curcol - newcol)):
x = True
if ((curcol < newcol) and (currow > newrow)): #NorthEast
x = diagnoal_check(board2d, currcol, currow, newcol, newrow, -1, 1)
elif ((curcol < newcol) and (currow < newrow)): #SouthEast
x = diagnoal_check(board2d, currcol, currow, newcol, newrow, 1, 1)
elif ((curcol > newcol) and (currow < newrow)): #SouthWest
x = diagnoal_check(board2d, currcol, currow, newcol, newrow, 1, -1)
elif ((curcol > newcol) and (currow > newrow)): #NorthWest
x = diagnoal_check(board2d, currcol, currow, newcol, newrow, -1, -1)
else:
x = False
return x
對於您在標題中的問題,對角循環遍歷列表並不復雜,只是您的用例使它變得更加困難,但通常可以通過以下方式實現:
for i in range(len(your_2d_list)):
print(your_2d_list[i][i])
由於range(start,stop,step)
function,這種方法不需要知道方向,綁定在列表理解中
def validate_move(matrix, cur_row, cur_col, new_row, new_col):
x = False
if abs(cur_row - new_row) == abs(cur_col - new_col):
# Create a mapping of points to analyse
crossed_points = [
[x for x in range(cur_row, new_row, 1 if new_row - cur_row >= 0 else -1)], # list of rows indexes
[y for y in range(cur_col, new_col, 1 if new_col - cur_col >= 0 else -1)], # list of columns indexes
]
# Check each crossed point to see if P is present
for point in range(len(crossed_points[0])):
if matrix[crossed_points[0][point]][crossed_points[1][point]] == "P":
x = True
# Stop the loop because P is found
break
else:
x = False
return x
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.