sni*_*erd 8 python dictionary python-3.x
我的代码有效,但我想知道是否有更多的pythonic方法来做到这一点.我有一本字典,我想看看是否:
因此,在我的代码中,"a","b"和"c"的键将成功,这是正确的.
import re
mydict = {
"a":"alpha",
"b":0,
"c":False,
"d":None,
"e":"",
"g":" ",
}
#a,b,c should succeed
for k in mydict.keys():
if k in mydict and mydict[k] is not None and not re.search("^\s*$", str(mydict[k])):
print(k)
else:
print("I am incomplete and sad")
Run Code Online (Sandbox Code Playgroud)
我上面所做的工作,但这似乎是一个非常长的条件.也许这只是正确的解决方案,但我想知道是否有更多的pythonic"存在且有东西"或更好的方法来做到这一点?
更新 感谢大家的精彩回答和深思熟虑的评论.有了一些要点和提示,我已经更新了一些问题,因为我没有的条件也应该成功.我还将示例更改为循环(更容易测试吗?).
尝试获取值并将其存储在变量中,然后使用对象"truthyness"继续使用该值
v = mydict.get("a")
if v and v.strip():
Run Code Online (Sandbox Code Playgroud)
"a"不在dict中,则get返回None并失败第一个条件"a"在dict但是yield None或者是空字符串,则测试失败,如果"a"产生一个空字符串,则strip()返回falsy字符串,它也会失败.让我们测试一下:
for k in "abcde":
v = mydict.get(k)
if v and v.strip():
print(k,"I am here and have stuff")
else:
print(k,"I am incomplete and sad")
Run Code Online (Sandbox Code Playgroud)
结果:
a I am here and have stuff
b I am incomplete and sad # key isn't in dict
c I am incomplete and sad # c is None
d I am incomplete and sad # d is empty string
e I am incomplete and sad # e is only blanks
Run Code Online (Sandbox Code Playgroud)
如果你的值可以包含False,0或其他"falsy"非字符串,你必须测试字符串,在这种情况下更换:
if v and v.strip():
Run Code Online (Sandbox Code Playgroud)
通过
if v is not None and (not isinstance(v,str) or v.strip()):
Run Code Online (Sandbox Code Playgroud)
所以如果没有条件匹配None,或者不是字符串(一切都匹配)或者如果是字符串,则字符串不是空白.