如何找到两个列表之间的公用子列表? [英] How do you find common sublists between two lists?
本文介绍了如何找到两个列表之间的公用子列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果子列表也存在于另一个列表中,您如何查找或仅保留列表的子列表?
How do you find or keep only the sublists of a list if it the sublist is also present within another list?
lsta = [['a','b','c'],['c','d','e'],['e','f','g']]
lstb = [['a','b','c'],['d','d','e'],['e','f','g']]
我想做类似set(lsta)&设置(lstb)
I'd like to do something like set(lsta) & set(lstb)
Desired_List = [['a','b','c'],['e','f','g']]
之所以要执行set之类的原因是因为它的速度,因为我在非常重要的大型列表中执行此操作.
The reason I'd like to do something like set is for it's speed as I'm doing this on a very large list where efficiency is quite important.
还有一点关系,如果我想从lsta中减去lstb以获得
Also, slightly unrelated, what if I wanted to subtract lstb from lsta to get
Desired_List2 = [['d','d','e']]
推荐答案
最好将列表列表更改为元组列表,然后可以轻松地使用set操作:
Better change the list of lists to list of tuples, then you can easily use the set operations:
>>> tupa = map(tuple, lsta)
>>> tupb = map(tuple, lstb)
>>> set(tupa).intersection(tupb)
set([('a', 'b', 'c'), ('e', 'f', 'g')])
>>> set(tupa).difference(tupb)
set([('c', 'd', 'e')])
这篇关于如何找到两个列表之间的公用子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文