Python3 用 if 判断列表是否为空的方法

Python3 用 if 判断列表是否为空的方法,第1张

用 if 进行判断,在Python中,False,0,‘’,[],{},()的布尔值都为0,if 后面为0 = 假,其余值 = 真
方法一

list = [] 
if list: # list不为0 可以进入
    print("不为空")
else:
    print("为空")

方法二

# list 有值为真,没值为假
list = []
if not list: #not 取反后空值为真
    print("为空")
if list: # list 为空时进不来这个 if 
    print("啥也不打印")
 
list = [1,2,3]
if list:
    print("不为空")

方法三
使用len()

_list = []
n = len(_list)
if n == 0:
    print("为空")
else:
    print("不为空")
 
# 上述代码简化为:
if n: # 0 为假,其余为真
    print("不为空")
else:
    print("为空")

方法四
用None来判断(先记下来,跟not一样)

_list = []
if _list is not None:
    print("***")
 
以上代码会 print 出来 ***,说明 _list 确实为空

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/868869.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存