[英]how to make a list of lists with difference between lists?
我列出了一些數字:
l1 = [1,2,3,4,5,6,7]
還有一個:
l2 = [3,5,6]
我想獲取包含在l2中但不存在於l1中的數字的間隔列表:
intervals = [[1,2],[4],[7]]
我試圖這樣做:
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
獲取間隔邊的列表,但是接下來呢?
您可以將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]]
使用集。 Python內置了集合數據結構。 您正在尋找的是與眾不同。 這是文檔。
所以set.difference(x,y)
https://docs.python.org/2/library/sets.html
讓我知道您是否還需要更多
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.