简体   繁体   中英

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
        else:
            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?

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]]

Use sets. Python has built in set data structures. What you are looking for is difference. Here is the documentation.

So set.difference(x,y)

https://docs.python.org/2/library/sets.html

Let me know if you need more than this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM