从1D列表中创建2D列表 [英] Create a 2D list out of 1D list

查看:92
本文介绍了从1D列表中创建2D列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python有点陌生,我想根据此matrixwidthlength将一维列表转换为二维列表.

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

说我有一个list=[0,1,2,3],我想为此列表做一个2 by 2矩阵.

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

如何从list中获取matrix [[0,1],[2,3]] width = 2,length = 2?

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

推荐答案

尝试类似的方法:

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]]

这篇关于从1D列表中创建2D列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆