349. 两个数组的交集|python

简介: 列表推导式很强大。def section(num1,num2): # 交集并集差集 alist = [i for i in num1 if i in num2] alist2 = [i for i in num1 if i not in num2] alist3 = list(set(num1).

列表推导式很强大。

def section(num1,num2):
    # 交集并集差集
    alist = [i for i in num1 if i in num2]
    alist2 = [i for i in num1 if i not in num2]
    alist3 = list(set(num1).union(set(num2)))

    print(alist,alist2,alist3)


if __name__ == '__main__':
    num1 = [4,9,5]
    num2 = [9,4,9,8,4]
    section(num1,num2)

结果:
[4, 9] [5] [4, 5, 8, 9]

目录
相关文章
|
1月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
73 2
|
23天前
|
存储 数据处理 索引
如何删除 Python 数组中的值?
【8月更文挑战第29天】
24 8
|
23天前
|
索引 Python
向 Python 数组添加值
【8月更文挑战第29天】
26 8
|
23天前
|
存储 缓存 C语言
|
23天前
|
存储 测试技术 Python
Python 数组和列表有什么区别?
【8月更文挑战第29天】
26 4
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
Leetcode题目"剑指 Offer 21. 调整数组顺序使奇数位于偶数前面"的两种Python解决方案,一种是使用双端队列调整数组顺序,另一种是使用双指针法将奇数移到数组前半部分,偶数移到后半部分。
21 4
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 11. 旋转数组的最小数字
解决剑指Offer 11题 "旋转数组的最小数字" 的三种Python实现方法:直接使用min函数、线性查找分界点和二分查找法,以找出旋转数组中的最小元素。
34 2
|
23天前
|
Python
python在列表、元素、字典、集合和numpy的数组前加上星号 * 是什么含义,以及*args和**kwargs的使用
python在列表、元素、字典、集合和numpy的数组前加上星号 * 是什么含义,以及*args和**kwargs的使用
24 0
|
1月前
|
Python
Python 数组比较
Python 数组比较
26 0
|
1月前
|
索引 Python
[Python]数组基础
[Python]数组基础