小编Har*_*ryM的帖子

elif 不适用于字典键值对

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

  • 类型不是整数或浮点数。即使该值是一个可以转换为整数(例如“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))
Run Code Online (Sandbox Code Playgroud)

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

20190101 5
20190102 6
type
20190103 7.5 …
Run Code Online (Sandbox Code Playgroud)

python if-statement

2
推荐指数
1
解决办法
47
查看次数

标签 统计

if-statement ×1

python ×1