python中列表、字典等为空方法主要有如下几种:
1 len方法判断。
2 利用空列表、空字典等相当于False的特点。
3 判断它是否等于另一个空列表、字典等。
例子:
lista = [1,2,3,4,5]
listb = []
listc = []
#用len判断列表的长度是否为零
if len(listb) == 0:
print('listb列表为空!')
#用于判断语句时,非空列表相当于True,空列表相当于False
if lista:
print('lista列表不是空!')
if not listb:
print('listb列表是空!')
#python中空列表都是相等的
if lista == listb:
print('lista和listb相同!')
if listb == listc:
print('listb和listc相同!')
#不用None来判断空列表,空列表不是None
if listb is not None:
print('listb is not None')
if lista is not None:
print('lista is not None')
结果:
listb列表为空!
lista列表不是空!
listb列表是空!
listb和listc相同!
listb is not None
lista is not None
例子2:
dicta = {'name':'张三','age':12}
dictb = {}
dictc = {}
print(type(dictb))
#用len判断字典的长度是否为零
if len(dictb) == 0:
print('dictb字典为空!')
#用于判断语句时,非空字典相当于True,空字典相当于False
if dicta:
print('dicta字典不是空!')
if not dictb:
print('dictb字典是空!')
#python中空字典都是相等的
if dicta == dictb:
print('dicta和dictb相同!')
if dictb == dictc:
print('dictb和dictc相同!')
#不用None来判断空字典,空字典不是None
if dictb is not None:
print('dictb is not None')
if dicta is not None:
print('dicta is not None')
结果:
<class 'dict'>
dictb字典为空!
dicta字典不是空!
dictb字典是空!
dictb和dictc相同!
dictb is not None
dicta is not None
文章讲述了在Python中如何使用len方法以及空列表、字典的特性来判断它们是否为空,同时介绍了空列表和字典之间的相等性以及与None的区别。
545

被折叠的 条评论
为什么被折叠?



