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

yipeiwu_com5年前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 中 function(#) (X)格式 和 (#)在Python3.*中的注意事项

python 的语法定义和C++、matlab、java 还是很有区别的。 1. 括号与函数调用 def devided_3(x): return x/3. print(a)...

Python提取转移文件夹内所有.jpg文件并查看每一帧的方法

python里面可以将路径里面的\替换成/避免转义。 os.walk方法可以将目标路径下文件的root,dirs,files提取出来。后面对每个文件进行操作。 切片操作[:]判断是否为....

Python开发的HTTP库requests详解

Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网...

Python 获取中文字拼音首个字母的方法

Python 获取中文字拼音首个字母的方法

Python:3.5 代码如下: def single_get_first(unicode1): str1 = unicode1.encode('gbk') try: ord...

Python获取网段内ping通IP的方法

问题描述 在某些问题背景下,需要确认是否多台终端在线,也就是会使用我们牛逼的ping这个命令,做一些的ping操作,如果需要确认的设备比较少,也还能承受。倘若,在手中维护的设备很多。那么...