gpt4 book ai didi

嵌套字典和列表的 Pythonic 替代品

转载 作者:太空宇宙 更新时间:2023-11-03 10:59:27 24 4
gpt4 key购买 nike

我目前正在使用自纪元以来以秒为单位的字典结合嵌套字典和列表来存储和查找事件。优点是我可以快速查找具有良好性能的值(想想哈希)。缺点是搜索和操作后续内容很笨拙。我忍不住认为我的方法不是很 Pythonic,所以我正在寻找建议。

这是一个使用整数而不是自纪元以来的秒数的简单示例:

D = {}

D[1] = {"995" : ["20905", "200101"]}
D[2] = {"991" : ["20901"], "995" : ["20905"]}

eventCode = '995'
error = '90900'

# find entry
if 1 in D:
# if eventCode exists then append error code
if D[1][eventCode]:
D[1][eventCode].append(error)

我可以快速查找 D[1],但是代码的其余部分似乎不是很 Pythonic。有什么建议还是我偏执?

我应该检查“错误”是否已经在列表中。但是,我不确定如何检查此构造中的成员资格。此代码段对我不起作用:

if error not in D[1][eventCode]

最佳答案

我不确定这是不是你想要的,但你可以使用 sets 更改列表处理重复项并使用 dict.get跳过检查 key 是否存在:

D = {"995" : {"20905", "200101"}}  # dict: str -> set

# 1) event code not exists, nothing changes:
D.get('111', set()).add('7777')
print(D) # {'995': {'20905', '200101'}}

# 2) event code exists, error already present, nothing changes:
D.get('995', set()).add('20905')
print(D) # {'995': {'20905', '200101'}}

# 3) event code exists, error not present, error will be added:
D.get('995', set()).add('7777')
print(D) # {'995': {'20905', '7777', '200101'}}

关于嵌套字典和列表的 Pythonic 替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35856421/

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