问题
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