Python将一维数组转换为二维数组

时间:2013-07-05 07:38:46

标签: python arrays multidimensional-array


我有一份清单
[1,2,3,4,5,6,7,8] 我想在python中将其转换为[[1,2,3,4] [5,6,7,8]]。有人可以帮助我吗

3 个答案:

答案 0 :(得分:7)

接受输入:

def chunks(l, n):
    return [l[i:i+n] for i in range(0, len(l), n)]

mylist = [1,2,3,4,5,6,7,8]
while 1:
    try:
        size = int(raw_input('What size? ')) # Or input() if python 3.x
        break
    except ValueError:
        print "Numbers only please"

print chunks(yourlist, size)

打印:

[[1, 2], [3, 4], [5, 6], [7, 8]] # Assuming 2 was the input

甚至:

>>> zip(*[iter(l)]*size) # Assuming 2 was the input
[(1, 2), (3, 4), (5, 6), (7, 8)]

答案 1 :(得分:3)

您可以使用itertools.islice

>>> from itertools import islice
def solve(lis, n):
     it = iter(lis)
     return [list(islice(it,n)) for _ in xrange(len(lis)/n)]
... 
>>> solve(range(1,9),4)
[[1, 2, 3, 4], [5, 6, 7, 8]]
>>> solve(range(1,9),2)
[[1, 2], [3, 4], [5, 6], [7, 8]]

答案 2 :(得分:3)

还有一种numpy方式(如果你的列表是一个统一的数字或字符串列表等)。

import numpy
a = numpy.array(lst)
nslices = 4
a.reshape((nslices, -1))