user2059300 user2059300 - 3 months ago 4
Python Question

Python - Convert a list to a list of lists

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?

Answer

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]]
Comments