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实现删除当前目录下除当前脚本以外的文件和文件夹实例

本文实例讲述了Python实现删除当前目录下除当前脚本以外的文件和文件夹。分享给大家供大家参考。具体如下: import os,sys import shutil cur_file...

Python下应用opencv 实现人脸检测功能

Python下应用opencv 实现人脸检测功能

使用OpenCV's Haar cascades作为人脸检测,因为他做好了库,我们只管使用。 代码简单,除去注释,总共有效代码只有10多行。 所谓库就是一个检测人脸的xml 文件,可以网...

Python3+PyInstall+Sciter解决报错缺少dll、html等文件问题

Python3+PyInstall+Sciter解决报错缺少dll、html等文件问题

1 调试过程 用Python3.6+Sciter+PyCharm写了一个py测试脚本helloworld.py,该脚本中只含有一条语句“import sciter”。在PyCharm中运...

Python的Django框架可适配的各种数据库介绍

在 Django 中使用 PostgreSQL 使用 PostgreSQL 的话,你需要从 http://www.djangoproject.com/r/python-pgsql/ 下载...

python中redis的安装和使用

python下redis安装 用python操作redis数据库,先下载redis-py模块下载地址https://github.com/andymccurdy/redis-py she...