最近工作中遇见了这个基础问题,分享一下。
以下是Python中的两个Dict。
x = {'a': 1, 'b': 2, 'c': 3}
y = {'a': 3, 'b': 1, 'd': 5}
我们需要用到class collections.Counter([iterable-or-mapping])
# 相加操作
re_1 = Counter(x) + Counter(y)
print(re_1)
# 相减操作
re_2 = Counter(x) - Counter(y)
print(re_2)
输出结果:
Counter({'a': 4, 'b': 3, 'c': 3, 'd': 5})
Counter({'b': 1, 'c': 3})
在结果中,a不见了,是因为输出会忽略掉结果为零或者小于零的计数。
如果对Counter其它内容有兴趣的,可以查看下面的参考链接。
参考链接:Python Counter