May-25-2019, 09:57 AM
I am trying to split a list of numbers into sublists once a condition is met.
num_list = [0,1,2,3,4,5,2,3,4,5,0,1,2,3,4,5,0,1,2,3,4,5]
Whenever the list reaches 5, it needs to be splitted as a sublist resulting as below:
[[0,1,2,3,4,5],[2,3,4,5],[0,1,2,3,4,5],[0,1,2,3,4,5]]
I tried the code below which seems to work but it places 5 into the following list and I can't figure out how to place it in the previous list instead.
num_list = [0,1,2,3,4,5,2,3,4,5,0,1,2,3,4,5,0,1,2,3,4,5]
Whenever the list reaches 5, it needs to be splitted as a sublist resulting as below:
[[0,1,2,3,4,5],[2,3,4,5],[0,1,2,3,4,5],[0,1,2,3,4,5]]
I tried the code below which seems to work but it places 5 into the following list and I can't figure out how to place it in the previous list instead.
num_list =[0,1,2,3,4,5,1,2,3,4,5,2,3,4,5] arrays = [[num_list[0]]] # array of sub-arrays (starts with first value) for i in range(1, len(num_list)): # go through each element after the first if num_list[i] != 5: # If it's larger than the previous arrays[len(arrays)-1].append(num_list[i]) # Add it to the last sub-array else: # otherwise arrays.append([num_list[i]]) # Make a new sub-array print(arrays)used from the solution given in this link: https://stackoverflow.com/questions/5255...-condition