gpt4 book ai didi

python - 从 defaultdict 获取原始 key 集

转载 作者:太空狗 更新时间:2023-10-29 22:20:58 26 4
gpt4 key购买 nike

有没有办法从 defaultdict 获取原始/一致的 key 列表,即使请求的 key 不存在?

from collections import defaultdict
>>> d = defaultdict(lambda: 'default', {'key1': 'value1', 'key2' :'value2'})
>>>
>>> d.keys()
['key2', 'key1']
>>> d['bla']
'default'
>>> d.keys() # how to get the same: ['key2', 'key1']
['key2', 'key1', 'bla']

最佳答案

你必须排除。具有默认值的键!

>>> [i for i in d if d[i]!=d.default_factory()]
['key2', 'key1']

与 Jean 建议的方法的时间比较,

>>> def funct(a=None,b=None,c=None):
... s=time.time()
... eval(a)
... print time.time()-s
...
>>> funct("[i for i in d if d[i]!=d.default_factory()]")
9.29832458496e-05
>>> funct("[k for k,v in d.items() if v!=d.default_factory()]")
0.000100135803223
>>> ###storing the default value to a variable and using the same in the list comprehension reduces the time to a certain extent!
>>> defa=d.default_factory()
>>> funct("[i for i in d if d[i]!=defa]")
8.82148742676e-05
>>> funct("[k for k,v in d.items() if v!=defa]")
9.79900360107e-05

关于python - 从 defaultdict 获取原始 key 集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45398212/

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