简体   繁体   中英

Print every row and column index for numpy matrix along with their values

I have a 2d matrix that shows the status of the seats in a theater, where S means the seat is vacant and B are the seats that are booked.

seats = [['S' 'B' 'B' 'S' 'S']
 ['S' 'S' 'S' 'S' 'S']
 ['S' 'B' 'B' 'B' 'S']
 ['S' 'S' 'S' 'S' 'S']
 ['S' 'B' 'S' 'B' 'S']]

I would like to print the results similar to the following manner which I need to store in a database:

seats[0][0] = 'S'
seats[0][1] = 'B'
.
.
.
seats[5][5] = 'S'

I am not aware of in which format you need the information but here is a way to go about it-

import numpy as np

seats = np.array([['S', 'B', 'B', 'S', 'S'],
                  ['S', 'S', 'S', 'S', 'S'],
                  ['S', 'B', 'B', 'B', 'S'],
                  ['S', 'S', 'S', 'S', 'S'],
                  ['S', 'B', 'S', 'B', 'S']])

indices = np.indices(seats.shape)
print(np.hstack((indices[0].reshape(-1, 1), indices[1].reshape(-1, 1), seats.reshape(-1, 1))))
[['0' '0' 'S']
 ['0' '1' 'B']
 ['0' '2' 'B']
 ['0' '3' 'S']
 ['0' '4' 'S']
 ['1' '0' 'S']
 ['1' '1' 'S']
 ['1' '2' 'S']
 ['1' '3' 'S']
 ['1' '4' 'S']
 ['2' '0' 'S']
 ['2' '1' 'B']
 ['2' '2' 'B']
 ['2' '3' 'B']
 ['2' '4' 'S']
 ['3' '0' 'S']
 ['3' '1' 'S']
 ['3' '2' 'S']
 ['3' '3' 'S']
 ['3' '4' 'S']
 ['4' '0' 'S']
 ['4' '1' 'B']
 ['4' '2' 'S']
 ['4' '3' 'B']
 ['4' '4' 'S']]
for i in range(len(seats)):
    for j in range(len(seats[i])):
        print(i,j, seats[i][j])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM