Python列表交集效率:generator还是filter()? [英] Python list intersection efficiency: generator or filter()?

查看:173
本文介绍了Python列表交集效率:generator还是filter()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Python(2.7)中的两个列表相交.我需要结果是可迭代的:

I would like to intersect two lists in Python (2.7). I need the result to be iterable:

list1 = [1,2,3,4]
list2 = [3,4,5,6]
result = (3,4) # any kind of iterable

提供完整迭代将在交点之后首先执行,以下哪一项效率更高?

Providing a full iteration will be performed first thing after the intersection, which of the following is more efficient?

使用发电机:

result = (x for x in list1 if x in list2)

使用filter():

Using filter():

result = filter(lambda x: x in list2, list1)

其他建议?

在此先感谢,
嫩农

Thanks in advance,
Amnon

推荐答案

都不是.最好的方法是使用集合.

Neither of these. The best way is to use sets.

list1 = [1,2,3,4]
list2 = [3,4,5,6]
result = set(list1).intersection(list2)

集合是可迭代的,因此无需将结果转换为任何东西.

Sets are iterable, so no need to convert the result into anything.

这篇关于Python列表交集效率:generator还是filter()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆