Python中list的交、并、差集获取方法示例

yipeiwu_com6年前Python基础

1. 获取两个list 的交集

# -*- coding=utf-8 -*-
 
#方法一:
a=[2,3,4,5]
b=[2,5,8]
tmp = [val for val in a if val in b]
print tmp
#[2, 5]
 
#方法二
print list(set(a).intersection(set(b)))

2. 获取两个list 的并集

print list(set(a).union(set(b)))

3. 获取两个list 的差集

print list(set(b).difference(set(a))) # b中有而a中没有的
print list(set(a).difference(set(b))) # a中有而b中没有的

总体代码及执行结果:

# -*- coding=utf-8 -*-
 
#方法一:
a=[2,3,4,5]
b=[2,5,8]
tmp = [val for val in a if val in b]
print tmp
#[2, 5]
 
#方法二
print list(set(a).intersection(set(b)))
 
print list(set(a).union(set(b)))
 
print list(set(b).difference(set(a))) # b中有而a中没有的
print list(set(a).difference(set(b))) # a中有而b中没有的

/usr/bin/python /Users/nisj/PycharmProjects/EsDataProc/mysql_much_tab_data_static.py
[2, 5]
[2, 5]
[2, 3, 4, 5, 8]
[8]
[3, 4]
 
Process finished with exit code 0

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python出现"IndentationError: unexpected indent"错误解决办法

python出现"IndentationError: unexpected indent"错误解决办法

python出现"IndentationError: unexpected indent"错误解决办法 Python是一种对缩进非常敏感的语言,最常见的情况是tab和空格的混用会导致错误...

python使用PyV8执行javascript代码示例分享

安装相应的库,我使用的是PyV8 需要注意的是里面写的function函数需要用()括起来 复制代码 代码如下:import PyV8 class Test():   ...

python输出决策树图形的例子

windows10: 1,先要pip安装pydotplus和graphviz: pip install pydotplus pip install graphviz 2,www.g...

Python处理Excel文件实例代码

因为工作需求,需要审核一部分query内容是否有效,query储存在Excel中,文本内容为页面的Title,而页面的URL以HyperLink的格式关联到每个Cell。 于是本能的想到...

零基础学Python(一)Python环境安装

任何高级语言都是需要一个自己的编程环境的,这就好比写字一样,需要有纸和笔,在计算机上写东西,也需要有文字处理软件,比如各种名称的OFFICE。笔和纸以及office软件,就是写东西的硬件...