简体   繁体   中英

How can I create a matrix from a list?

I am given a list which somehow represents a matrix, but it is in the list format, like

["OOX","XOX","XOX"]

Is there any way i can convert it into a matrix? I have gone through numpy, but could not figure out!

numpy is overkill for this. For something like Tic-tac-toe, a list of lists is enough.

If 'OOX' is a string, then list('OOX') is the list ['O','O','O'] .

You can combine list with a list comprehension:

Something like:

>>> rows =  ["OOX","XOX","XOX"]
>>> board = [list(row) for row in rows]
>>> board
[['O', 'O', 'X'], ['X', 'O', 'X'], ['X', 'O', 'X']]

Used like:

>>> board[0][2]
'X' (3rd entry in first row).

Note that lists are mutable, so the elements can be changed as well as read:

board[0][2] = 'O' will change the 'X' in that position to an 'O' .

As simple as this:

In [4]: a = ["OOX","XOX","XOX"]

In [5]: m = np.array([*map(list, a)])

In [6]: m
Out[6]: 
array([['O', 'O', 'X'],
       ['X', 'O', 'X'],
       ['X', 'O', 'X']], 
      dtype='<U1')

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