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

Vig*_*esh 2 python arrays multidimensional-array


我有一个列表
[1,2,3,4,5,6,7,8]
我想在python中将其转换为[[1,2,3,4] [5,6,7,8]].有人可以帮我这个

Ter*_*ryA 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)
Run Code Online (Sandbox Code Playgroud)

打印:

[[1, 2], [3, 4], [5, 6], [7, 8]] # Assuming 2 was the input
Run Code Online (Sandbox Code Playgroud)

甚至:

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