[]不是None
是一个易错点,用代码来看:
1
2
3
4
5
6
7aaa = []
print(aaa is True) # 输出False
if (aaa := []): # Python 3.8多了一个类似golang的生命方法,等于"aaa=[] if aaa is True"
print("22222", aaa,aaa is not None)
else:
print("11111",aaa,aaa is None) # 会走到这里
那么判断list是否是一个空集,除了用len
之外,是可以直接用True
来做的:
1
2
3
4
5
6
7
8l1 = ["Hire", "the", "top", "1%", "freelancers"]
l2 = []
if l2:
print("list is not empty")
else:
print("list is empty")
或者用bool()
,原理一样:
1
2
3
4
5
6
7
8l1 = ["Hire", "the", "top", "1%", "freelancers"]
l2 = []
if bool(l2):
print("list is empty")
else:
print("list is not empty")
而且注意的是aaa = [None]
这样的aaa也不是None
,啥样的情况会出现None
?比如bbb=aaa.sort()
,那么这个bbb就是None
。