Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.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:添加字典项。_Python_Dictionary - Fatal编程技术网

Python:添加字典项。

Python:添加字典项。,python,dictionary,Python,Dictionary,当我们添加字典项时 我们使用的是x.items()+y.items(),但有些东西我不明白 比如说 如果x={2:2,1:3}和y={1:3,3:1}x.items()+y.items()给出{3:1,2:2,1:3} 因此,正如你所看到的,数学上的答案可能是6x+2x^2+x^3 但字典给出了x^3+2x^2+3x 有谁能告诉我更好的方法吗?让我们弄清楚这里发生了什么 In [7]: x.items() Out[7]: [(1, 3), (2, 2)] In [8]: y.items() O

当我们添加字典项时

我们使用的是
x.items()+y.items()
,但有些东西我不明白

比如说

如果
x={2:2,1:3}
y={1:3,3:1}
x.items()+y.items()
给出
{3:1,2:2,1:3}

因此,正如你所看到的,数学上的答案可能是
6x+2x^2+x^3

但字典给出了
x^3+2x^2+3x


有谁能告诉我更好的方法吗?

让我们弄清楚这里发生了什么

In [7]: x.items()
Out[7]: [(1, 3), (2, 2)]

In [8]: y.items()
Out[8]: [(1, 3), (3, 1)]

In [9]:  x.items() + y.items()
Out[9]: [(1, 3), (2, 2), (1, 3), (3, 1)]

In [10]: dict(x.items() + y.items())
Out[10]: {1: 3, 2: 2, 3: 1}
items()
生成一个(键、值)元组列表,并且
+
连接这些列表。然后,您可以将该列表返回到字典中,字典将通过使用给定键获取最后一个值来处理重复键。因为这一次它是一个重复的值,所以这无关紧要,但它可以:

In [11]: z = {1:4, 3:1}

In [12]: dict(x.items() + z.items())
Out[12]: {1: 4, 2: 2, 3: 1}
在这种情况下,1:3条目将被丢弃


(不清楚你对多项式的类比是什么……如果你真的想表示以算术方式相加的多项式,你可能想查看类或@adw描述的
集合。Counter

你可以创建自己的
dict
子类来实现add操作符:

import copy
class AddingDict(dict):
    def __add__(self, d2):
        new_dict = copy.deepcopy(self)
        for key, value in d2.iteritems():
            if key in new_dict:
                new_dict[key] += value
            else:
                new_dict[key] = value
        return new_dict
现在:

>>> x = AddingDict({2:2,1:3})
>>> y = AddingDict({1:3,3:1})
>>> x+y
{1: 6, 2: 2, 3: 1}
编辑

如果您需要额外的效率,检查原始密钥中每个密钥的
新目录中是否有每个密钥是无效的,您可以将每个密钥列表转换为
集合
,并进行交叉,但代码会更复杂,效率可能不需要。实际的实现留给读者作为练习。

当您调用
dict(x.items()+y.items())
时,重复的键只需设置两次,最新的设置值(来自
y
的设置值)覆盖旧的设置值(来自
x

既然Python字典可以有任何东西作为它的键或值(只要键是可散列的),那么它怎么知道在替换键时如何组合新旧值呢

在Python2.7和3中,有一个名为
Counter
的字典子类,它只能将数字作为值。当您将其中两个加在一起时,它会将重复键的值加在一起:

>>> from collections import Counter
>>> Counter({2:2,1:3}) + Counter({1:3,3:1})
Counter({1: 6, 2: 2, 3: 1})

你需要更好地解释当你“添加”字典时你期望得到什么,特别是为什么你期望它做你认为它应该做的事情而不是它实际做的事情……你是谁(“我们”)以及为什么你使用
x.items()+y.items()
来“添加”两个字典?