How do you find common sublists between two lists? [duplicate]

女生的网名这么多〃 提交于 2019-12-23 18:10:25

问题


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

I'd like to do something like set(lsta) & set(lstb)

Desired_List = [['a','b','c'],['e','f','g']]

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.

Also, slightly unrelated, what if I wanted to subtract lstb from lsta to get

Desired_List2 = [['d','d','e']]

回答1:


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



回答2:


If your sub-lists need to remain lists, use a list comprehension

Intersection:

>>> [i for i in lsta if i in lstb]
[['a', 'b', 'c'], ['e', 'f', 'g']]

Subtraction:

>>> [i for i in lsta if i not in lstb]
[['c', 'd', 'e']]



回答3:


I have written a C module a while ago for this:

>>> lsta = [['a','b','c'],['c','d','e'],['e','f','g']]
>>> lstb = [['a','b','c'],['d','d','e'],['e','f','g']]
>>> list(boolmerge.andmerge(lsta, lstb))
>>> import boolmerge
[['a', 'b', 'c'], ['e', 'f', 'g']]

This is O(n) time, and require the lists to be sorted.



来源:https://stackoverflow.com/questions/21448310/how-do-you-find-common-sublists-between-two-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!