Python:找出第x个元素在m×n的矩阵的位置

x是位置序号,从行开始,从左到右的顺序

def find_row_col(index, rows, cols):
    """找出index在rows*cols的矩阵中第几行第几列"""
    row_index = index // cols  # Integer division gives the row index
    col_index = index % cols  # Remainder gives the column index
    
    if row_index == 0:
        row_index = row_index + 1
    elif col_index > 0:
        row_index = row_index + 1

    if col_index == 0:
        col_index = cols

    return row_index, col_index

你可能感兴趣的:(Python,python,算法)