gpt4 book ai didi

python - 为什么我可以使用按位 AND 检查列表是否包含字典的键?

转载 作者:行者123 更新时间:2023-12-02 04:18:25 24 4
gpt4 key购买 nike

我偶然发现了这个问题Python - intersection between a list and keys of a dictionary ,不幸的是没有所需的声誉来询问:

为什么会这样?

d1 = {'200:200':{'foo':'bar'},'300:300':{'foo':'bar'}}
l1 = ['200:200', '90:728']
keys = d1.keys() & l1

最佳答案

d1.keys() 的结果是一个类似 View 的集合。

Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as set-like since the entries are generally not unique.) For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).

来自https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects

& 的第二个参数只需要是可哈希对象的可迭代对象(尽管文档中没有说明)。

参见https://docs.python.org/3/library/stdtypes.html#set.intersection

关于python - 为什么我可以使用按位 AND 检查列表是否包含字典的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32144787/

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