python求两个列表的交集_Python中两个列表的有序交集

I know that in Python, if I have:

list_1 = [1,2,3]

list_2 = [2,3,4]

I can do the following to find the intersection between the two:

list(set(list_1) & set(list_2))

# = [2,3]

But there's one problem with that approach: sets don't maintain order the way that lists do. So if I actually have:

list_1 = [3,2,1]

list_2 = [2,3,4]

I get:

list(set(list_1) & set(list_2))

# = [2,3]

even though I'd prefer to have the order from the first list, ie.:

# = [3,2]

Is there an alternative intersection technique which keeps the resulting "intersection set" in the same order as the first list?

解决方案set_2 = frozenset(list_2)

intersection = [x for x in list_1 if x in set_2]

set instead of frozenset works too, I'm just increasingly in the habit of using immutable classes in cases where I don't intend to mutate the data. The point is that to maintain order you need to traverse the list in the order you want to maintain, but you don't want to have the n*m complexity of the naive approach: [x for x in list_1 if x in list_2]. Checking for membership in a set or similar hash-based type is roughly O(1), compared to O(n) for membership in a list.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值