False 有人能指出为什么会这样吗? 谢谢, Rajarshi 打坐: pyisinstance(False,int) 真 pyisinstance([],int) False pybool([]) False James 写作,if x是写作的缩写如果bool(x)。 评估bool(x)检查x .__非零__() 如果该方法不是''定义后,它会检查 x .__ len __()以查看x是否为非空容器。 在您的情况下,写入if []"转换为 " if len([])!= 0",其评估结果为False。 正确和错误的类型为bool,这是一个子类 of int。所以,False确实等于零和 真实等于一。 相反,空列表不是int类型。 /> 所以[]!= False eventHough bool([])== False。 Raymond This is a slightly naive question, but I know that 0 can be used torepresent False. SoTrueBut, I know I can use [] to represent False as in....emptyBut then doing the following gives a surprising (to me!) resultFalseCould anybody point out why this is the case?Thanks,Rajarshi 解决方案TrueBut, I know I can use [] to represent False as in...emptyBut then doing the following gives a surprising (to me!) resultFalseCould anybody point out why this is the case?"if foo:" does not check if "foo == True" or "foo == False" but rather"bool(foo)". For empty lists, strings, tuples, dicts and some other things,"bool(foo) == False", while for lists, etc., with at least one element,"bool(foo) == True".--Robert Kern"I have come to believe that the whole world is an enigma, a harmless enigmathat is made terrible by our own mad attempt to interpret it as though it hadan underlying truth."-- Umberto EcoTrueBut, I know I can use [] to represent False as in...emptyBut then doing the following gives a surprising (to me!) resultFalseCould anybody point out why this is the case?Thanks,RajarshiMeditate on:pyisinstance(False, int)Truepyisinstance([], int)Falsepybool([])FalseJamesWriting, "if x" is short for writing "if bool(x)".Evaluating bool(x) checks for a x.__nonzero__()and if that method isn''t defined, it checks forx.__len__() to see if x is a non-empty container.In your case, writing "if []" translates to"if len([]) != 0", which evaluates to False.True and False are of type bool which is a subclassof int. So, False really is equal to zero andTrue really is equal to one.In contrast, the empty list is not of type int.So [] != False eventhough bool([]) == False.Raymond 这篇关于0 == False但是[]!= False?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 11:44
查看更多