gpt4 book ai didi

python - 检查字典的链式实现中的值

转载 作者:行者123 更新时间:2023-12-01 03:32:37 25 4
gpt4 key购买 nike

我有一个字典,它对具有相同键的值使用链接,这意味着 dict[key] = [object1, object2, object3,..., object n]

我有两个对象year0year1。我需要查找 year0year1 是否在字典中的某个键上。

如果 year0year1 不可用,那么我应该继续下一个键。注意:year0year1 是两个不同的对象。

不幸的是,我不断收到各种错误,例如在分配之前引用的对象,或者我无法继续处理下一个键。

下面是我的代码以获取更多信息:

rateLst = []
if year1 > year0:
for reg in data.keys():
slots = data[reg] #slots = [(object[year, index]), object[year, index]
for value in slots: #value = object[year, index]
if value.year == year0:
index0 = value.index
if value.year == year1:
index1 = value.index
if index1 is None or index0 is None: #error occurs even if I initialize the values as well it doesn't work
pass
else:
gRate = cagr([index0, index1], year1 - year0)
rateLst.append((reg, gRate))
return rateLst

谢谢<3

最佳答案

rateLst = []
if year1 > year0:
index0, index1 = None, None
for reg, slots in data.items():
#slots = data[reg] #slots = [(object[year, index]), object[year, index]
for value in slots: #value = object[year, index]
if value.year == year0:
index0 = value.index
if value.year == year1:
index1 = value.index
if index1 is None or index0 is None: #error occurs even if I initialize the values as well it doesn't work
pass
else:
# You are using OR operator above so there is a chance that index0 or index1 would be None, not sure if this is intended or not
gRate = cagr([index0, index1], year1 - year0)
rateLst.append((reg, gRate))
return rateLst

关于python - 检查字典的链式实现中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40700592/

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