Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何使用python 3从字典中减去字典?_Python 3.x_Dictionary - Fatal编程技术网

Python 3.x 如何使用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} >

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}
>>> dict3 = {key:dict1[key]-dict2[key] for key in dict1}
>>> dict3
{'key2': 4, 'key1': -3, 'key3': 1}
当然,我没有处理错误:

  • dict 2中缺少键(
    defaultdict
    可以解决)
  • dict 1中缺少键(可能可以吗?)
  • 你可以理解:

    >>> 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}
    
    当然,我没有处理错误:

  • dict 2中缺少键(
    defaultdict
    可以解决)
  • dict 1中缺少键(可能可以吗?)

  • 您可以使用
    集合
    模块

    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(勾选向上投票按钮下的符号)。谢谢