PYTHON中对列表list求交集
来源:互联网 发布:禾川plc编程软件下载 编辑:程序博客网 时间:2024/04/30 12:36
方法1
遍历b1,如果某个元素同时也存在于b2中,则返回
b1=[1,2,3]
b2=[2,3,4]
b3 = [val for val in b1 if val in b2]
print b3
运行结果如下
dwapp@pttest1:/home/dwapp>python t1.py
[2, 3]
方法2
把列表转换为集合,利用集合操作符求出交集,然后再转换回列表类型
b1=[1,2,3]
b2=[2,3,4]
b3=list(set(b1) & set(b2))
print b3
运行结果如下
dwapp@pttest1:/home/dwapp>python t1.py
[2, 3]
前面的例子中两个list都是简单的单元素列表,还有一种比较特殊的情况,就是有嵌套类型的
b1=[1,2,3]
b2=[[2,4],[3,5]]
b3 = [filter(lambda x: x in b1,sublist) for sublist in b2]
print b3
运行结果如下
dwapp@pttest1:/home/dwapp>python t1.py
[[2], [3]]
下面是文档中对filter的解释
filter(function, iterable)
Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.
- PYTHON中对列表list求交集
- Python中对列表list求交集
- python中求两个List的交集、并集和差集
- python 两个list 求交集,并集,差集
- python 两个list 求交集,并集,差集
- Python 求两个 list 的交集和差集
- python list 求交集 差集 并集
- python 对中文文件求交集、并集、差集
- 在python中对list求和及求积
- list字符串操作求交集
- Python对列表list的操作
- python 求两个list的差集,并集和交集
- Python求两个list的差集、交集与并集的方法
- Python求两个list的差集、交集与并集的方法
- Python求两个list的差集、交集与并集的方法(转)
- python 求两个list的差集,并集和交集
- JAVA集合类List求交集
- Java两个list求交集的方法
- 使用JQuery写了个小插件
- XML的替换符
- 可设置行距的Label
- 用VC2005编译非VC工程
- apache tomcat 的配置
- PYTHON中对列表list求交集
- The Safest Investment 最安全的投资
- Android Sensors Development
- linux下如何实现简单刷屏
- PCI设备配置空间问题
- Paxos算法
- 透过HAL(硬件抽象层)看顶层API是如何访问硬件
- Android中G-Sensor相关流程
- 哈尔滨工业大学—仪器科学与技术考研专业课