1

I'm trying to create a list of lists, such that each inner list has 8 elements, in a python one-liner.

So far I have the following:

locations = [[alphabet.index(j) for j in test]]

That maps to one big list inside of a list:

[[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]]

But I want to split it up to be multiple inner lists, each 8 elements:

[[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16]]

Any idea how I can acheive this?

user2059300
  • 361
  • 1
  • 5
  • 17
  • 3
    Possible duplicate of [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – Mephy Aug 14 '16 at 03:50

2 Answers2

1

Use list slicing with range() to get the starting indexes:

In [3]: test = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

In [4]: [test[i:i+8] for i in range(0, len(test), 8)]
Out[4]: [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16]]

As a function:

In [7]: def slicing(list_, elem_):
   ...:     return [list_[i:i+elem_] for i in range(0, len(list_), elem_)]

In [8]: slicing(test, 8)
Out[8]: [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16]]
heemayl
  • 39,294
  • 7
  • 70
  • 76
  • That works in two steps, but is there a way to make it all one? If not this will work, but for learning purposes I'd like to find a way to do it all in one step. – user2059300 Aug 14 '16 at 03:57
  • @user2059300 good request - the style you are reffering to is known as the [pythonic way.](http://blog.startifact.com/posts/older/what-is-pythonic.html) The original answer above is pretty good. There might be an itertools way of doing this too... – theQuestionMan Aug 14 '16 at 04:54
0

Another solution could be to use NumPy

import numpy as np

data = [x for x in xrange(0, 64)]
data_split = np.array_split(np.asarray(data), 8)

Output:

for a in data_split:
    print a

[0 1 2 3 4 5 6 7]
[ 8  9 10 11 12 13 14 15]
[16 17 18 19 20 21 22 23]
[24 25 26 27 28 29 30 31]
[32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47]
[48 49 50 51 52 53 54 55]
[56 57 58 59 60 61 62 63]
Sunil
  • 97
  • 5
  • 11