自学Python:python判断元组、列表、字典是否为空的if语句

在学习pythons时,遇到列表是否为空的判断语句,如下代码,对if后面只跟列表名(if requested_toppings:)比较疑惑。

requested_toppings = []
if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding " + requested_topping + ".")
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")

查了资料,发现这是列表是否为空的判断语句的一种写法,还有很多写法,这里记录下其他的写法。

判断一个 list 是否为空:

传统的方式:

    if len(mylist):
        # Do something with my list
    else:
        # The list is empty

由于一个空 list 本身等同于 False,所以可以直接:

    if mylist:
        # Do something with my list
    else:
        # The list is empty

python判断元组、列表、字典是否为空的代码,在python中()、[]、{}、0、''、False都会是,所以出现这些情况时,就好判断是不是为空了。

#!/usr/bin/python
# -*- coding: utf-8 -*-
p1 = () #空元组
p2 = [] #空列表
p3 = {} #空字典
p4 = 0  #变量0
p5 = '' #变量空字符串
p6 = False #变量假
 
if p1 :
    print 'p1非空'
else:
    print 'p1空'
    
#print "p1的类型" 
#print type(p1)
 
if p2 :
    print 'p2非空'
else:
    print 'p2空'
    
#print "p2的类型" 
#print type(p2)
 
if p3 :
    print 'p3非空'
else:
    print 'p3空'
    
#print "p3的类型"
#print type(p3)
 
if p4 :
   print '0为真'
else:
   print '0为假'
   
#print "p4的类型" 
#print type(p4)
 
if p5 :
   print '空字符串为真'
else:
   print '空字符串为假'
   
#print "p5的类型" 
#print type(p5)
 
if p6 :
   print 'False真'
else:
   print 'False为假'
   
#print "p6的类型" 
#print type(p6)

通过len()

list_test = []
if len(list_test):
    print('list_test 为非空list')  # 存在值即为True
else:
    print('list_test 为空list')  # 不存在值即为FALSE

直接通过 if+list 判断

list_test = []
if list_test:
    print('list_test 为非空list')  # 存在值即为True
else:
    print('list_test 为空list')  # 不存在值即为FALSE

 list == [ ] 也是可行的,不过会有Expression can be simplified提示

list_test = []
if list_test == []:
    print('list_test 为非空list')  # 存在值即为True
else:
    print('list_test 为空list')  # 不存在值即为FALSE

收集于网络

版权声明:
作者:水东柳
链接:https://shuidl.com/2115.html
来源:水东柳博客
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
< <上一篇
下一篇>>