Python 3.x 如何使用python 3从字典中减去字典?
Python 3不支持以下内容:Python 3.x 如何使用python 3从字典中减去字典?,python-3.x,dictionary,Python 3.x,Dictionary,Python 3不支持以下内容: dict1 = {key1:6, key2:7, key3:5} dict2 = {key1:9, key2:3, key3:4} dict3 = dict1 - dict2 那么如何从python 3中的字典中减去字典呢?您可以理解它: >>> dict1 = {'key1':6, 'key2':7, 'key3':5} >>> dict2 = {'key1':9, 'key2':3, 'key3':4} >
dict1 = {key1:6, key2:7, key3:5}
dict2 = {key1:9, key2:3, key3:4}
dict3 = dict1 - dict2
那么如何从python 3中的字典中减去字典呢?您可以理解它:
>>> dict1 = {'key1':6, 'key2':7, 'key3':5}
>>> dict2 = {'key1':9, 'key2':3, 'key3':4}
>>> dict3 = {key:dict1[key]-dict2[key] for key in dict1}
>>> dict3
{'key2': 4, 'key1': -3, 'key3': 1}
当然,我没有处理错误:
defaultdict
可以解决)>>> dict1 = {'key1':6, 'key2':7, 'key3':5}
>>> dict2 = {'key1':9, 'key2':3, 'key3':4}
>>> dict3 = {key:dict1[key]-dict2[key] for key in dict1}
>>> dict3
{'key2': 4, 'key1': -3, 'key3': 1}
当然,我没有处理错误:
defaultdict
可以解决)您可以使用
集合
模块
Ex:
from collections import Counter
dict1 = Counter({"key1":6, "key2":7, "key3":5})
dict2 = Counter({"key1":9, "key2":3, "key3":4})
dict1.subtract(dict2)
print(dict1)
Counter({'key2': 4, 'key3': 1, 'key1': -3})
输出:
from collections import Counter
dict1 = Counter({"key1":6, "key2":7, "key3":5})
dict2 = Counter({"key1":9, "key2":3, "key3":4})
dict1.subtract(dict2)
print(dict1)
Counter({'key2': 4, 'key3': 1, 'key1': -3})
您可以使用
集合
模块
Ex:
from collections import Counter
dict1 = Counter({"key1":6, "key2":7, "key3":5})
dict2 = Counter({"key1":9, "key2":3, "key3":4})
dict1.subtract(dict2)
print(dict1)
Counter({'key2': 4, 'key3': 1, 'key1': -3})
输出:
from collections import Counter
dict1 = Counter({"key1":6, "key2":7, "key3":5})
dict2 = Counter({"key1":9, "key2":3, "key3":4})
dict1.subtract(dict2)
print(dict1)
Counter({'key2': 4, 'key3': 1, 'key1': -3})
这不处理负数!这么奇怪(也许是意料之中?)。很酷的解决方案。啊,解决了,太棒了。如果它解决了你的问题,请接受ans(勾选向上投票按钮下的符号)。谢谢这不处理负数!这么奇怪(也许是意料之中?)。很酷的解决方案。啊,解决了,太棒了。如果它解决了你的问题,请接受ans(勾选向上投票按钮下的符号)。谢谢