ilaunchpad ilaunchpad - 1 month ago 4
Python Question

Divide the list in chunks (sub-lists) based on filter criterion

I have a list like this

a = ['31', '20', '54', '68', '65', '72', '00', '00', '00', '82', '4d', '61', '72', '67', '69', '6e', '00', '00', '00', '00','00', '84', '92', '4d','91']


I want to split them into list of tuples and remove the chunk of zeros.

li_tup = [('31', '20', '54', '68', '65', '72'), ('82', '4d', '61', '72', '67', '69', '6e'), ('84', '92', '4d','91')]


When I use the
splice[index:index]
the original list remains the same. So the loop iterates over the same item. How do I remove the spliced items from the original list? So I dont have to iterate over it again.

Answer

Here's a list comprehension answer that doesn't require importing itertools:

>>> a = ['31', '20', '54', '68', '65', '72', '00', '00', '00', '82', '4d', '61', '72', '67', '69', '6e', '00', '00', '00', '00','00', '84', '92', '4d','91']
>>> [ tuple(b.strip().split()) for b in ' '.join(a).split('00 ') if b ]
[('31', '20', '54', '68', '65', '72'), ('82', '4d', '61', '72', '67', '69', '6e'), ('84', '92', '4d', '91')]

Comparison with other other approaches (for 10,000 iterations):

  • This approach using joining and splitting takes - 0.214s
  • MosesKoledoye's answer using itertools.groupby() with for loop takes - 0.372s,
  • anonymous's answer using itertools.groupby() with list comprehension takes - 0.321s

(not including the time it takes for their codes to import itertools)

Comments