python两个集合的交集_Python中两个嵌套列表的交集

I've a problem with the nested lists. I want to compute the lenght of the intersection of two nested lists with the python language. My lists are composed as follows:

list1 = [[1,2], [2,3], [3,4]]

list2 = [[1,2], [6,7], [4,5]]

output_list = [[1,2]]

How can i compute the intersection of the two lists?

解决方案

I think there are two reasonable approaches to solving this issue.

If you don't have very many items in your top level lists, you can simply check if each sub-list in one of them is present in the other:

intersection = [inner_list for inner in list1 if inner_list in list2]

The in operator will test for equality, so different list objects with the same contents be found as expected. This is not very efficient however, since a list membership test has to iterate over all of the sublists. In other words, its performance is O(len(list1)*len(list2)). If your lists are long however, it may take more time than you want it to.

A more asymptotically efficient alternative approach is to convert the inner lists to tuples and turn the top level lists into sets. You don't actually need to write any loops yourself for this, as map and the set type's & operator will take care of it all for you:

intersection_set = set(map(tuple, list1)) & set(map(tuple, list2))

If you need your result to be a list of lists, you can of course, convert the set of tuples back into a list of lists:

intersection_list = list(map(list, intersection_set))

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值