insomniaqq insomniaqq - 1 year ago 58
Python Question

how to make a list of lists with difference between lists?

I have a list of some numbers:

l1 = [1,2,3,4,5,6,7]

and another one:

l2 = [3,5,6]

I wanna get the list of intervals with numbers which exist are in the l2, but not in l1:

intervals = [[1,2],[4],[7]]

I've tried to do it like this:

current_common_line_no = 0
for line in l1:
if line in l2:
current_common_line_no = line
next_common_line_no = l2[(l2.index(current_common_line_no))+1]
print next_common_line_no

to get list of interval edges, but what next?

Answer Source

You can use groupby() with list-comprehension:

from itertools import groupby    
[list(g) for k, g in groupby(l1, key=lambda x: x not in l2) if k]
# [[1, 2], [4], [7]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download