Slicing a list into sublists based on condition

  • A+
Category:Languages

I want to slice this list of numbers:

num_list = [97, 122, 99, 98, 111, 112, 113, 100, 102]  

into multiple sublists. The condition for slicing is that the numbers in each sublist should be in increasing order.

So the final result will look like this:

 list_1 = [97, 122]  list_2 = [99]  list_3 = [98, 111, 112, 113]  list_4 = [100, 102] 

Can anyone help me to solve this problem please? Thanks a lot

 


Creating a variable number of variables is not recommended. Use a list of lists or dictionary instead. Here's an example with dict and a generator function:

from itertools import zip_longest  def yield_lists(L):     x = []     for i, j in zip_longest(L, L[1:], fillvalue=L[-1]):         x.append(i)         if i > j:             yield x             x = []     yield x  num_list = [97, 122, 99, 98, 111, 112, 113, 100, 102]  res = dict(enumerate(yield_lists(num_list), 1)) 

Resut:

{1: [97, 122],  2: [99],  3: [98, 111, 112, 113],  4: [100, 102]} 

For example, access the second list via res[2].

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: