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)
运行结果: