Turning a list into nested lists in python

Possible duplicate:
How to convert a list to an array in python?

How to include a list, for example:

data_list = [0,1,2,3,4,5,6,7,8]

to a list of lists, for example:

new_list = [ [0,1,2] , [3,4,5] , [6,7,8] ]

those. I want to group ordered items in a list and store them in an ordered list. How can i do this?

thank

+5
source share
5 answers

This assumes the data_list is a multiple of three

i=0
new_list=[]
while i<len(data_list):
  new_list.append(data_list[i:i+3])
  i+=3
+10
source

This groups each 3 elements in the following order:

new_list = [data_list[i:i+3] for i in range(0, len(data_list), 3)]

Give us the best example if this is not what you want.

+30
source

- :

map (lambda x: data_list[3*x:(x+1)*3], range (3))
+5
source

new_list = [data_list[x:x+3] for x in range(0, len(data_list) - 2, 3)]

List understanding of winning :)

+2
source

Do you have any selection criteria from your original list?

Python allows you to do this:

new_list = []
new_list.append(data_list[:3])
new_list.append(data_list[3:6])
new_list.append(data_list[6:])

print new_list
# Output:  [ [0,1,2] , [3,4,5] , [6,7,8] ]
0
source

All Articles