3


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

Vignesh
  • 912
  • 6
  • 13
  • 24
  • What kind of transformation do you want to apply? Do you just want to split it in the middle? – user2357112 Jul 05 '13 at 07:40
  • Is there a way to split it based on a user input?? if he says 4 then the 1d array is split into 2x4. or if he says 2 then there will be a 2d array of dimension 4x2?? – Vignesh Jul 05 '13 at 07:42

3 Answers3

9

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)]
TerryA
  • 58,805
  • 11
  • 114
  • 143
4

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]]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
4

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))
shx2
  • 61,779
  • 13
  • 130
  • 153