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 random all_choioces = ['石头', '剪刀', '布'] win_list...

TensorFlow实现AutoEncoder自编码器

TensorFlow实现AutoEncoder自编码器

一、概述 AutoEncoder大致是一个将数据的高维特征进行压缩降维编码,再经过相反的解码过程的一种学习方法。学习过程中通过解码得到的最终结果与原数据进行比较,通过修正权重偏置参数降低...

Python的randrange()方法使用教程

 choice()方法从一个列表,元组或字符串返回一个随机项。 语法 以下是choice()方法的语法: choice( seq ) 注意:此函数是无法直接访问的,所...

windows下python安装小白入门教程

windows下python安装小白入门教程

本文记录了windows下python的安装,供大家参考,具体内容如下 —–因为我是个真小白,网上的大多入门教程并不适合我这种超级超级小白,有时候还会遇到各种各样的问题,因此记录一下我的...

python3.5 + PyQt5 +Eric6 实现的一个计算器代码

python3.5 + PyQt5 +Eric6 实现的一个计算器代码

目前可以实现简单的计算。计算前请重置,设计的时候默认数字是0,学了半天就做出来个这么个结果,bug不少。 python3.5 + PyQt5 +Eric6 在windows7 32位系统...