现在的位置: 首页 > 综合 > 正文

004_017 Python 查找2个字典的交集和并集 指的是键

2017年12月10日 ⁄ 综合 ⁄ 共 405字 ⁄ 字号 评论关闭

代码如下:

#encoding=utf-8

print '中国'

#查找2个字典的交集和并集 指的是键

dict1={1:2,2:3}
dict2={1:2,4:3}

#并集
union = dict(dict1,**dict2)
print union


#交集
#for要用循环次数小的 可以提高性能
inter = dict.fromkeys([x for x in dict1 if x in dict2])
print inter


#set 并集
set1={1,2}
set2={1,2,3,4}

print set1 | set2
print set1.union(set2)
#set 交集
set1={1,2}
set2={1,2,3,4}

print set1 & set2
print set1.intersection(set2)

打印结果如下:

中国
{1: 2, 2: 3, 4: 3}
{1: None}
set([1, 2, 3, 4])
set([1, 2, 3, 4])
set([1, 2])
set([1, 2])

抱歉!评论已关闭.