Python:添加字典项目。
当我们添加字典项目,Python:添加字典项目。
我们使用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项被丢弃......
(看不清你的比喻多项式是......如果你真的要表示添加算术多项式,你可能要检查出numpy类由@adw描述poly1d或collections.Counter
。)
你可以创建自己的dict
子类来实现将运算符添加到d啊,你想要的东西:
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}
编辑
如果你需要额外的效率,检查是否每个键是在new_dict
每个键在原来是效率低下,并且您可以将每个密钥列表转换为set
并采用交叉点,但代码会更复杂,效率可能不需要。实际执行情况仅供读者参考。
当您拨打dict(x.items()+y.items())
时,重复键只需设置两次,最新设置值(来自y
的那个值)会覆盖较旧的值(从x
)。
由于Python字典可以包含任何东西作为它的键或值(只要键可哈希),它将如何知道在键被替换时如何组合旧值和新值?
在Python 2.7和3中,有一个名为Counter
的字典子类,它只能有数字作为值。而当你的那些添加两个在一起,那不添加值一起重复键:
>>> from collections import Counter
>>> Counter({2:2,1:3}) + Counter({1:3,3:1})
Counter({1: 6, 2: 2, 3: 1})
你需要更好地解释你期望得到什么,当你“添加”词典,特别是你为什么希望它做你认为它应该,而不是它实际上做什么...... – 2010-11-05 14:43:39
你是谁(“我们”),为什么你使用'x.items()+ y.items()'来“添加”两个字典? – tzot 2010-11-07 09:37:11