Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list to list of list for adjacent numbers

Tags:

python

list

  • 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], []]

like image 474
sim Avatar asked Oct 25 '25 10:10

sim


1 Answers

You can use itertools.groupby:

from itertools import groupby

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

out = [
    list(v for _, v in g)
    for _, g in groupby(enumerate(l), key=lambda v: v[0] - v[1])
]
print(out)

Prints:

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

Without itertools.groupby:

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

out = [[l[0]]]
for i in range(1, len(l)):
    if l[i] - out[-1][-1] == 1:
        out[-1].append(l[i])
    else:
        out.append([l[i]])

print(out)

Edit: Added .sort()

like image 121
Andrej Kesely Avatar answered Oct 27 '25 00:10

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!