Python返回真假值(True or False)——类似C# “? true : false”

python源码如下:

arr=['a','b','c']
if len(arr)==0:
	isFind=False
else:
	isFind=True

在C#中,以上代码可用一句话表示:

hasLen=(arr.length==0)? false : true

感觉在Python中也应该有此类代码,找了些资料终于让我找到了:

# 方法1:
hasLen=False if len(arr)==0 else True
# 方法2:
hasLen=[False,True][len(arr)==0]

输出结果:

方法2原理:布尔值True被索引求值为1,而False就等于0。
len(arr)==0为false,因此取0位置的值,即False。

网址:https://www.aliyun.com/jiaocheng/485043.html

你可能感兴趣的:(python)