记录Python条件判断if语句的一个问题

版权声明:如对本文有疑问请联系作者微信kxymxzs,欢迎骚扰! https://blog.csdn.net/MG_ApinG/article/details/89513635
nbrList1=[]
if nbrList1:
    print('gg')
if nbrList1 and 5 < len(nbrList1[0][0]) < 30:
    print('gg')
if 5 < len(nbrList1[0][0]) < 30:
    print('gg')
Traceback (most recent call last):
  File "D:\APP\python36\lib\site-packages\IPython\core\interactiveshell.py", line 3267, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-6-f53920ca42b6>", line 1, in <module>
    if 5 < len(nbrList1[0][0]) < 30:
IndexError: list index out of range

前两个判断语句不会报错,可正常执行,最后一个报IndexError错误,第二个可以用来判断不知道list是否为空的情况下进一步判断,在某种情况下能用到,比如我要取几个list中元素长度大于20的list,如果把判断是否空list和长度判断分开,整个循环就会有很多问题,一起判断的话几个elif就完事了,写爬虫可能比较常遇到这类情况。

猜你喜欢

转载自blog.csdn.net/MG_ApinG/article/details/89513635
今日推荐