Python中列表字典的差集、交集、并集

一、列表的交并差集

a = [1,2,5,7]
b = [2,5,9]

"""
**两个列表的差集**
"""
 ①、第一种方法
ret = list(set(a)^set(b))
print(ret)      #[1, 7, 9]

#②、第二种方法
ret = []
for i in a:
    if i not in b:
        ret.append(i)
print(ret)      #[1, 7]

#③、第三种方法
ret = [i for i in a if i not in b ]
print(ret)      #[1, 7]

#④、第四种方法
print(list(set(a).difference(set(b)))) # a中有而b中没有的  #[1, 7]

#⑤、第五种方法
ret2=list(set(a)-set(b))
print(ret2)     #[1, 7]

"""
**两个列表的交集**
"""
#①、第一种方法
print (list(set(a).intersection(set(b))))  #[2, 5]

#②、第二种方法
ret = [i for i in a if i in b ]
print(ret)                          #[2, 5]

#③、第三种方法
ret = []
for i in a:
    if i in b:
        ret.append(i)
print(ret)                      #[2, 5]
#④、第四种方法
ret2= list(set(a) & set(b))
print(ret2)                 #[2, 5]


"""
**两个列表的并集**
"""
#①、第一种方法
print(list(set(a).union(set(b))))           #[1, 2, 5, 7, 9]

#②、第二种方法
ret2= list(set(a) | set(b))
print(ret2)             #[1, 2, 5, 7, 9]
"""
**统计列表中某一数据出现的次数**
"""
a = [1,2,272,7,1,2,45,3,6,45,2]
print(a.count(0))

二、字典的交并差集

a = { 'x': 1,'y': 2,'z': 3}

b = {'w': 10,'x': 11,'y': 2}

print('交集相同的键:', a.keys() & b.keys())
print('差集键:', a.keys() - b.keys())
print('并集键', a.keys() | b.keys())

print('key和value的交集:', a.items() & b.items())
print('a中存在的b不存在:', a.items() - b.items())
print('key和value的并集:', a.items() | b.items())
输出:
		交集相同的键: {'y', 'x'}
		差集键: {'z'}
		并集键 {'y', 'x', 'z', 'w'}
		key和value的交集: {('y', 2)}
		a中存在的b不存在: {('z', 3), ('x', 1)}
		key和value的并集: {('x', 11), ('x', 1), ('w', 10), ('y', 2), ('z', 3)}

版权声明:本文为weixin_42579328原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。