0
点赞
收藏
分享

微信扫一扫

Python判断一个数据结构是否为空的方法

《Effective Python》,里面提到判断字符串或者集合是否为空的原则。


意思是:
不要通过取字符串或者集合的长度来判断是否为空,而是要用not关键字来判断,因为当字符串或集合为空时,其值被隐式地赋为False.

test_str=''
test_tuple=()
test_list=[]
test_dict={}
test_set=set()
if not(test_str):
    print("字符串为空")
if not(test_tuple):
    print("元组为空")
if not(test_list):
    print("列表为空")
if not(test_dict):
    print("字典为空")
if not(test_set):
    print("集合为空")
=====================================
输出结果:
	字符串为空
	元组为空
	列表为空
	字典为空
	集合为空

 

 

举报

相关推荐

0 条评论