Har*_*ryM 2 python if-statement
我正在编写一个函数来清理字典数据,其中包含一个键值对,显示日期和该日期的降雨量。数据清洗的条件需要去除和键值对满足以下条件的值:
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
added
20190104 0
20190105 -7
20190106 102
20190107 1
{'20190103': 7.5}
Run Code Online (Sandbox Code Playgroud)
很多键值对都没有像我期望的那样使用 elif 语句。例如,我无法弄清楚为什么 20190101 5 的第一个键值对通过所有 if/elif 语句 put 没有添加到新字典中,或者为什么 20190105 -7 键值对通过 elif 语句值小于 0。当我将所有这些语句更改为 if 语句而不是 elif 语句时,代码可以工作,但公平地说,我可以判断这些语句是互斥的,因此 elif 应该可以工作。我希望代码只运行一个 if 或 elif 语句,如果满足一个条件,我不需要它运行所有这些语句。我不明白 elifs 不起作用?
5 of20190101 5不是浮动的,所以它进入第一个分支
if not type(inches) == float:
Run Code Online (Sandbox Code Playgroud)
既然进入了这里,就不会进入任何elifs。
的520190101 5是整数,所以这部分也不会执行:
if not type(inches) == int:
print ("type")
continue
Run Code Online (Sandbox Code Playgroud)
如果您的要求是
类型不是整数或浮点数。
(实际上应该是:类型既不是 integer 也不是 float)
用 if not type(inches) == float and not type(inches) == int:
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |