python 条件表达式中的疏散命令
evacuation order in python condition expression
a=[]
b=[]
c= a[0],b if a else (None,None)
d= (a[0],b) if a else (None,None)
第一个表达式会引发 IndexError,但第二个是 fine.How 它发生了吗。
带有 IndexError
的代码行正在评估 a[0]
的值,而其后的代码行则不是。
对于行:
c= a[0],b if a else (None,None)
发生的情况如下:
变量 c
被赋值 a[0]
和 if
语句 b if a else (None,None)
.
的值
为此,该行必须评估 a[0]
.
中的值
对于行:
d= (a[0],b) if a else (None,None)
a[0]
的值尚未评估。因为 if
语句没有到达将尝试评估 a[0]
.
中的值的元组
如果您要将行更改为:
d= (a[0],b) if True else (None,None)
你还会得到一个 IndexError
a=[]
b=[]
c= a[0],b if a else (None,None)
d= (a[0],b) if a else (None,None)
第一个表达式会引发 IndexError,但第二个是 fine.How 它发生了吗。
带有 IndexError
的代码行正在评估 a[0]
的值,而其后的代码行则不是。
对于行:
c= a[0],b if a else (None,None)
发生的情况如下:
变量 c
被赋值 a[0]
和 if
语句 b if a else (None,None)
.
的值
为此,该行必须评估 a[0]
.
对于行:
d= (a[0],b) if a else (None,None)
a[0]
的值尚未评估。因为 if
语句没有到达将尝试评估 a[0]
.
如果您要将行更改为:
d= (a[0],b) if True else (None,None)
你还会得到一个 IndexError