Nicole
Nicole

Reputation: 49

merge 2D array into a list python

What I want to do is to turn a 2D array like this:

np.array([[ 0, 1, 2, 3], [ 1, 5, 6, 7]])

into this (a list with all numbers in):

[0,1,2,3,1,5,6,7]

is there any way to make it happen?

Upvotes: 2

Views: 7519

Answers (2)

Clarius
Clarius

Reputation: 1419

Using 'raw' Python I was writing a simple player vs computer Tic Tac Toe game. The board was a 2D array of cells numbered 1 - 9. Player would select a cell to put their 'X' in. Computer would randomly select a cell to put their 'O' in from the remaining available cells. I wanted to transform the 2D board in a 1D list. Here's how.

>>> board=[["1","2","O"],["4","X","6"],["X","O","9"]]
>>> [ board[row][col] for row in range(len(board)) for col in range(len(board[row])) if board[row][col] != "X" if board[row][col] != "O" ]
['1', '2', '4', '6', '9']
>>> 

Upvotes: 0

tom10
tom10

Reputation: 69242

x = np.array([[ 0, 1, 2, 3], [ 1, 5, 6, 7]])    

list(x.flat)    # if you want a list
#  [0, 1, 2, 3, 1, 5, 6, 7]

x.flatten()  # if you want a numpy array
#   array([0, 1, 2, 3, 1, 5, 6, 7])

It's unclear to me whether you want a list or numpy array, but they are both easy to get (although I assume you want a list since you tagged this question with list). It's reasonable to pick whichever you want or is most useful to you.

For many uses, numpy has significant advantages over lists, but there are also times that lists work better. For example, in many constructions, one gets items one at a time and doesn't know ahead of time the size of the resulting output array, and in this case it can make sense to build a list using append and then convert it to a numpy array to take an FFT.

There are other approaches to converting between lists and numpy arrays. When you have the need to do things to be different (eg, faster), be sure to look at the documentation or ask back here.

Upvotes: 3

Related Questions