简体   繁体   English

如何使列表之间的差异列表?

[英]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: 我想获取包含在l2中但不存在于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: 您可以将groupby()与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. Python内置了集合数据结构。 What you are looking for is difference. 您正在寻找的是与众不同。 Here is the documentation. 这是文档。

So set.difference(x,y) 所以set.difference(x,y)

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

Let me know if you need more than this 让我知道您是否还需要更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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