Turning a list into nested lists in python
49,712
Solution 1
This assumes that data_list has a length that is a multiple of three
i=0
new_list=[]
while i<len(data_list):
new_list.append(data_list[i:i+3])
i+=3
Solution 2
This groups each 3 elements in the order they appear:
new_list = [data_list[i:i+3] for i in range(0, len(data_list), 3)]
Give us a better example if it is not what you want.
Solution 3
Something like:
map (lambda x: data_list[3*x:(x+1)*3], range (3))
Solution 4
Based on the answer from Fred Foo, if you're already using numpy
, you may use reshape
to get a 2d array without copying the data:
import numpy
new_list = numpy.array(data_list).reshape(-1, 3)
Solution 5
new_list = [data_list[x:x+3] for x in range(0, len(data_list) - 2, 3)]
List comprehensions for the win :)
Author by
Double AA
Updated on May 12, 2021Comments
-
Double AA about 3 years
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
-
eat almost 13 yearsFWIW, this won't be very practical one, when you try to generalize the pattern OP described. Thanks
-
Manny D almost 13 yearsOh I didn't know if the OP was wondering if embedded lists were possible in Python or if there was a way to convert a list into one.
-
Joe Ferndz over 3 yearsI fixed the code. lots of errors. However, I am not sure if this solves the problem. downvoting the answer.
-
Sindhukumari P about 3 years@JoeFerndz can i know what you have fixed in this ? have you run the code?
-
Sindhukumari P about 3 yearsBecause I remember writing the working code. What changes have you done?
-
Todd over 2 yearsI ran into a similar situation to the above question and your code worked perfect! I've been struggling at the last stage. So glad that I could address this.
-
Nils Mackay about 2 yearsI like this, but it only works when the array has a number of elements that's a multiple of 3, otherwise it will throw a ValueError.