gpt4 book ai didi

python - 对 python 字典键 View 的限制集操作

转载 作者:太空狗 更新时间:2023-10-30 01:00:04 24 4
gpt4 key购买 nike

让我们看看下面的代码片段:

d = {1:1}
keys = d.keys()

print(keys & {1,2,3})# {1}
d[2] = 2
print(keys & {1,2,3}) # {1,2} # keys() is a view/reference
print({1,2}.issubset({1,2,3})) # True
print(keys.issubset({1,2,3})) # 'dict_keys' object has no attribute 'issubset'

dictionary view objects上的官方文档中提到了它:

Keys views are set-like since their entries are unique and hashable. .. Then these set operations are available (“other” refers either to another view or a set): [&,|, ^, ^]

如果键是类似集合的,为什么对它们的集合操作仅限于那四个中缀操作。例如,为什么不允许像 issupersetissubset 这样的无副作用操作?

最佳答案

Why, for example, are not side-effect free operation like issuperset or issubset operation not permitted?

他们是;你只需要使用 >=<=运营商:

print(keys <= {1, 2, 3})

他们还支持isdisjoint在方法形式中,因为它没有运算符:

print(keys.isdisjoint({1, 2, 3}))

关于python - 对 python 字典键 View 的限制集操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38755358/

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