gpt4 book ai didi

python - 为什么 Python 字典不支持 '+' 运算符

转载 作者:行者123 更新时间:2023-11-28 18:29:06 26 4
gpt4 key购买 nike

我一直在思考为什么 Python 语言的标准 dict 类不支持加法/减法运算符,例如“+”或“+=”,例如

>>> foo = {'a': 1, 'b': 2}
>>> bar = {'c': 3, 'd': 4}

>>> foo + bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

我一厢情愿的想法是以下结果:

>>> foo + bar 
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

同样,为什么 __radd__(self, other) 的结果与 self.__update__(other) 的结果不一样?

>>> foo += bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +=: 'dict' and 'dict'

有谁知道默认行为的历史原因?

(我承认在 foobar 具有相同的键但不同的键值的情况下应该使用哪个值可能是不明确的)

最佳答案

Does anyone know the historic reasons for the default behaviour?

Guido van Rossum 评论说他更喜欢 update() 并且认为 + 运算符不会清楚地读取代码。

FWIW,他确实批准了PEP 448这为您提供了另一种使用星形拆包概括来做到这一点的方法:

>>> a = {'a': 1, 'b': 2}
>>> b = {'c': 3, 'b': 4}
>>> {**a, **b}
{'a': 1, 'b': 4, 'c': 3}

+ 可能不是一个好主意的原因有很多。通常,我们期望加法是可交换的,但只要存在具有不同值的重叠键,字典加法就会失败。 “正常”用例是仅就地更新 dict,但 + 的通常语义会复制两个输入的内容以创建一个新的 dict(这有点浪费)。

另外,Python 有collections.ChainMap它用可能进行多次查找的新费用取代了复制费用。

关于python - 为什么 Python 字典不支持 '+' 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38972503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com