Possible Duplicate:
How can I turn a list into an array in python?
How can I turn a list such as:
data_list = [0,1,2,3,4,5,6,7,8]
into a list of lists such as:
new_list = [ [0,1,2] , [3,4,5] , [6,7,8] ]
ie I want to group ordered elements in a list and keep them in an ordered list. How can I do this?
Thanks
This groups each 3 elements in the order they appear:
Give us a better example if it is not what you want.
new_list = [data_list[x:x+3] for x in range(0, len(data_list) - 2, 3)]
List comprehensions for the win :)
Something like:
Do you have any sort of selection criteria from your original list?
Python does allow you to do this:
Based on the answer from Fred Foo, if you're already using
numpy
, you may usereshape
to get a 2d array without copying the data:This assumes that data_list has a length that is a multiple of three