【python】并集交集
2024-09-07 16:52:39
set是用来去重的。
在list里使用union函数。这种方式不适用于元素为字典的。
list(set(a)^set(b)) 这是求差集
所以交集就是并集和ab的差集。
import random def getRand(n):
return [random.randint(0,100) for i in range(int(n))] a = getRand(10)
b = getRand(10) print(a)
print(b) c = list(set(a).union(set(b)))
print("ab的并集是:")
print(c) print("ab的交集是:")
d = list( (set(a).union(set(b))) ^ set(a) ^ set(b))
print(d)
列表生成式
emmm...记得函数和函数之间空两行,被教育了
import random def getRand(n):
return [random.randint(0,100) for i in range(int(n))] def union(a,b):
return [x for x in set(a+b)] def inter(a,b):
return [x for x in set(a) if x in set(b)] def main():
a = getRand(10)
b = getRand(10)
a = list(set(a))
b = list(set(b))
c = union(a,b)
d = inter(a,b)
print(a)
print(b)
print("并集是:")
print(c)
print("交集是:")
print(d)
main()
最新文章
- editplus如何插入当前时间_Ctrl+D
- 前端代码优化: 使用YUI Compressor
- Android中为窗口定义主题
- BZOJ 1207 打鼹鼠
- Strange Country II 暴力dfs
- ACM Wooden Stricks
- 轮播swiper配置选项
- netfilter的笔记3--那些内置的表
- Django添加ckeditor富文本编辑器
- Exp4 恶意代码分析 20155223
- Hbuilder MUI里面使用java.net.URL发送网络请求,操作cookie
- Python3的__new__进行构造类的实例化
- style=";visibility: hidden";和 style=“display:none”之间的区别
- 【C#/WPF】Button按钮动态设置Background背景颜色
- Docker--从安装到搭建环境
- 解决在django中应用keras模型时出现的ValueError(";Tensor %s is not an element of this graph."; % obj)问题
- iOS应用内付费(IAP)开发步骤
- 13-----BBS论坛
- shell中set命令
- 8、SRR数据下载https://ftp-trace.ncbi.nlm.nih.gov/sra/sdk/2.8.2/