Python 从一维列表中创建一个二维列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14681609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:08:40  来源:igfitidea点击:

Create a 2D list out of 1D list

pythonmatrix

提问by PhoonOne

I am a bit new to Python and I want to convert a 1D list to a 2D list, given the widthand lengthof this matrix.

我对 Python 有点陌生,鉴于this的widthlength,我想将一维列表转换为二维列表matrix

Say I have a list=[0,1,2,3]and I want to make a 2 by 2matrix of this list.

假设我有一个list=[0,1,2,3],我想制作2 by 2这个列表的矩阵。

How can I get matrix [[0,1],[2,3]]width=2, length=2 out of the list?

我怎样才能得到matrix [[0,1],[2,3]]width=2, length=2 list

采纳答案by root

Try something like that:

尝试这样的事情:

In [53]: l = [0,1,2,3]

In [54]: def to_matrix(l, n):
    ...:     return [l[i:i+n] for i in xrange(0, len(l), n)]

In [55]: to_matrix(l,2)
Out[55]: [[0, 1], [2, 3]]

回答by wim

I think you should use numpy, which is purpose-built for working with matrices/arrays, rather than a list of lists. That would look like this:

我认为你应该使用 numpy,它是专门为处理矩阵/数组而不是列表列表而构建的。那看起来像这样:

>>> import numpy as np
>>> list_ = [0,1,2,3]
>>> a = np.array(list_).reshape(2,2)
>>> a
array([[0, 1],
       [2, 3]])
>>> a.shape
(2, 2)

Avoid calling a variable listas it shadows the built-in name.

避免调用变量,list因为它隐藏了内置名称。

回答by Manik Dhingra

NumPy's built-in reshape function can be used to do such a task.

NumPy 的内置 reshape 函数可以用来完成这样的任务。

import numpy

length = 2
width = 2
_list = [0,1,2,3]
a = numpy.reshape(a, (length, width))
numpy.shape(a)

As long as you change the values within your list, and accordingly update the values of 'length' and 'width', you shouldn't receive any error.

只要您更改列表中的值,并相应地更新“长度”和“宽度”的值,您就不会收到任何错误。