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

标签 python python-3.x dictionary

我有一个字典,它对具有相同键的值使用链接,这意味着 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/

相关文章:

javascript - 尝试从数组中获取随机图像,取而代之的是所有相同的图像

python - 类型错误 : can only concatenate str (not "list") to str

python - 如何根据条件更改python数据框中的值(即列表)?

string - 从没有空格和标点符号的字符串中取消连接单词的算法

c# - C# 中的双射字典/映射

Python - 为什么我不能在 print 函数中使用生成器?

python - 如何实现 Pygame 定时游戏循环?

python - 我的单层感知器收敛于OR数据集,而不收敛于AND数据集

python - 在 PyQt 中读取文件

python - 函数返回两个值,将一个值存储在变量中,并将另一个值添加到变量中