Python transforming one dimensional array into two dimensional array [duplicate]

房东的猫 提交于 2021-02-07 09:06:16

问题



I have a list
[1,2,3,4,5,6,7,8]
I want to convert this as [[1,2,3,4][5,6,7,8]] in python. Can somebody help me with this


回答1:


To take an input:

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)

Prints:

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

Or even:

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



回答2:


You can use 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]]



回答3:


There's also the numpy way (if your list is a uniform list of numbers or strings, etc.).

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


来源:https://stackoverflow.com/questions/17483557/python-transforming-one-dimensional-array-into-two-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!