Python 判断是否为空

我们都知道Python从美感的角度讲究Pythonic,之前用java刷Leetcode,每次第一行考虑异常输入时都会写如下代码

if(s == null ||"".equals(s)):
    return or throw new Exception();

相对应的,Python也会想当然地按照如下方式去写:

对于字符串:

if s is None or s=='':
    return

对于列表:

if lst is None or len(lst)==0:
    return

其实不需要这样麻烦,我们只需要一种通用地判断就可以了

if not input:
    return

因为not None==True,not ''==True,not []==True,我试了下,对于int(0), set,dict,甚至双向队列deque都适用.

猜你喜欢

转载自www.cnblogs.com/tianyadream/p/12548873.html
今日推荐