如何在Python中理解None,[],[1]?

时间:2019-03-19 02:02:47

标签: python

我现在对第1、2和3块的输出感到困惑,它们之间的关系是什么? output of some code

3 个答案:

答案 0 :(得分:3)

这称为short-circuit evaluation

如果您有{ "images": [ { "id": 10, "name": "img1" }, { "id": 11, "name": "img2" } ] } A and B的值等于False,则该表达式将简单地返回A(为False或等效值)并跳过A。但是,如果B是True等价的,我们将返回A的值,因为B对于整个表达式的值不再重要。

类似地,对于A,如果我们有or并且A or B是True等价的,A将被跳过,B将返回表达。或者,如果A等于False,则返回A

答案 1 :(得分:1)

例如:您可以在Python控制台中完成

>>>a = None
>>>b = []
>>>c = [1]
>>>type(a)
<class 'NoneType'>
>>>type(b)
<class 'list'>
>>>type(c)
<class 'list'>

b和c具有相同的类型列表,并且a属于'NoneType'

b是一个空列表,b中没有元素,None是Python中的特殊对象,您会看到布尔值(False = 0,True = 1),

>>>b is None
>>> False
>>>len(b) 
>>> 0

>>>if b is not None:
       print(b)
   else:
       print(b,"is None")
>>>[]  #(b is empty, but it's not None)

您也可以这样做:

>>>b.append(a)
>>>b
>>>[None]
>>>len(b)
>>>1  #(b have one element None)

答案 2 :(得分:0)

从现在开始,我将更新所有这些False等效代码。

结论:

今天是2019年3月24日,星期日。

  • NaN不等于False,因为print(float('NaN') and False)给出了False

(今天是2019年3月19日,星期二。)

  • -1不等于False,因为 print(-1 and False) False

  • not 1, [], None, 0是False等效的,因为 print(not -1) print([] and False) print(None and False) print(0 and False) 分别是False, [], None, 0

相关问题