gpt4 book ai didi

python - 为什么 python dict 键/值不像鸭子一样嘎嘎叫?

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:33 26 4
gpt4 key购买 nike

Python 是 duck typed ,通常这可以避免在处理原始对象时强制转换 faff。

The canonical example (and the reason behind the name) is the duck test: If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.

然而,一个值得注意的异常(exception)是字典键/值,它看起来像鸭子并且像鸭子一样游泳,但值得注意的是不会像鸭子一样嘎嘎

>>> ls = ['hello']
>>> d = {'foo': 'bar'}
>>> for key in d.keys():
.. print(key)
..
'foo'
>>> ls + d.keys()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "dict_keys") to list

谁能告诉我这是为什么?

最佳答案

字典键实际上实现了集合的接口(interface)而不是列表的接口(interface),因此您可以直接对其他集合执行字典键的集合操作:

d.keys() & {'foo', 'bar'} # returns {'foo'}

但它没有实现__getitem____setitem____delitem__insert方法,这些方法是需要像列表一样“嘎嘎”,因此如果不先显式转换为列表,它就无法执行任何列表操作:

ls + list(d.keys()) # returns ['hello', 'foo']

关于python - 为什么 python dict 键/值不像鸭子一样嘎嘎叫?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52836113/

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