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

758次阅读
没有评论

共计 1378 个字符,预计需要花费 4 分钟才能阅读完成。

在学习 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

收集于网络

正文完
 
水东柳
版权声明:本站原创文章,由 水东柳 2019-06-20发表,共计1378字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)