简体   繁体   English

将二维数组合并到一个列表python中

[英]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]]) 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] [0,1,2,3,1,5,6,7]

is there any way to make it happen?有没有办法让它发生?

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 ).我不清楚你是想要一个列表还是 numpy 数组,但它们都很容易获得(尽管我假设你想要一个列表,因为你用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.对于许多用途, numpy 比列表具有显着优势,但有时列表效果更好。 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.例如,在许多构造中,一次获取一个项目并且不提前知道结果输出数组的大小,在这种情况下,使用append构建一个列表然后将其转换为numpy 数组进行 FFT。

There are other approaches to converting between lists and numpy arrays.还有其他方法可以在列表和 numpy 数组之间进行转换。 When you have the need to do things to be different (eg, faster), be sure to look at the documentation or ask back here.当您需要做一些不同的事情(例如,更快)时,请务必查看文档或在此处询问。

Using 'raw' Python I was writing a simple player vs computer Tic Tac Toe game.使用“原始”Python 我正在编写一个简单的玩家与计算机井字游戏。 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.棋盘是一个 2D 单元格数组,编号为 1 - 9。玩家将选择一个单元格将其“X”放入其中。计算机将从剩余的可用单元格中随机选择一个单元格将其“O”放入其中。 I wanted to transform the 2D board in a 1D list.我想将 2D 板转换为 1D 列表。 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']
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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