Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert list to list of list for adjacent numbers

  • i have list [31, 32,33, 1,2,3,4, 11,12,13,14]
  • I need to put into adjacent numbers into one list for i, i+1

Expected out [[1,2,3,4], [11,12,13,14], [31, 32,33]]

l = [31, 32,33, 1,2,3,4, 11,12,13,14]
l.sort() #sorted the items
new_l = []
for i in l:
    temp_l = []  # temp list before appending to main list
    if i + 1 in l: # if i + 1 is present append to temp_list
        temp_l.append(i)
    new_l.append(temp_l) # temp_l has to append to main list

My out is wrong : [[1], [2], [3], [], [11], [12], [13], [], [31], [32], []]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can append an empty sub-list to the output list when the difference between the current number and the last number in the last sub-list in the output list is not 1, and keep appending the current number to the last sub-list of the output list:

l = [31, 32,33, 1,2,3,4, 11,12,13,14]
l.sort()

output = []
for i in l:
    if not output or i - output[-1][-1] != 1:
        output.append([])
    output[-1].append(i)

output becomes:

[[1, 2, 3, 4], [11, 12, 13, 14], [31, 32, 33]]

Demo: https://replit.com/@blhsing/UnimportantValidTelecommunications

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading