elif 不适用于字典键值对

时间:2021-04-28 08:46:18

标签: python if-statement

我正在编写一个函数来清理字典数据,其中包含一个键值对,显示日期和该日期的降雨量。数据清洗的条件需要去除和键值对满足以下条件的值:

  • 类型不是整数或浮点数。即使价值 是一个可以转换为整数的字符串(例如 "5") 应该删除。
  • 值小于 0:不可能有 负降雨量,所以这一定是坏数据。
  • 值大于100:世界纪录 一天的降雨量为 71.8 英寸
def clean_data (adic):
    newDic = {}
    for (date,inches) in adic.items():  
        print (date,inches)
        if not type(inches) == float:
            if not type(inches) == int:
                print ("type")
                continue
        elif inches < 0:
            print ("below 0")
            continue
        elif inches > 100:
            print ("above 100")
            continue
        else:
            print ("added")
            newDic[date]=inches
    return newDic



rainfall = {"20190101": 5, "20190102": "6", "20190103": 7.5, 
           "20190104": 0, "20190105": -7, "20190106": 102,
           "20190107": 1}
print(clean_data(rainfall))

出于某种原因,我的代码正在输出:

20190101 5
20190102 6
type
20190103 7.5
added
20190104 0
20190105 -7
20190106 102
20190107 1
{'20190103': 7.5}

很多键值对都没有像我期望的那样使用 elif 语句。例如,我无法弄清楚为什么 20190101 5 的第一个键值对通过所有 if/elif 语句 put 没有添加到新字典中,或者为什么 20190105 -7 键值对通过 elif 语句值小于 0。当我将所有这些语句更改为 if 语句而不是 elif 语句时,代码可以工作,但公平地说,我可以判断这些语句是互斥的,因此 elif 应该可以工作。我希望代码只运行一个 if 或 elif 语句,如果满足一个条件,我不需要它运行所有这些语句。我不明白 elifs 不起作用?

2 个答案:

答案 0 :(得分:5)

20190101 5 的 5 不是浮点数,所以进入第一个分支

    if not type(inches) == float:

既然进入了这里,就不会进入任何elif

20190101 5 的 5 是整数,所以这部分执行:

        if not type(inches) == int:
            print ("type")
            continue

如果您的要求是

<块引用>

类型不是整数或浮点数。

(实际上应该是:类型既不是整数也不是浮点数

使用if not type(inches) == float and not type(inches) == int:

答案 1 :(得分:2)

rainfall = {"20190101": 5, "20190102": "6", "20190103": 7.5, 
           "20190104": 0, "20190105": -7, "20190106": 102,
           "20190107": 1}

5, 0, -7, 102, 1int 的类型。 if not type(inches) == float 的第一个 if 语句会处理它,因为它们是 int,它们不会转到 if 语句 if not type(inches) == int:

"6" 是字符串,既不是 float 也不是 int。所以它会打印类型消息。

唯一可以正确处理的元素是 7.5