例如,如果通过以下步骤:
a = []
如何检查a是否为空?
例如,如果通过以下步骤:
a = []
如何检查a是否为空?
当前回答
我曾写道:
if isinstance(a, (list, some, other, types, i, accept)) and not a:
do_stuff
投票结果为-1。我不确定这是否是因为读者反对这一策略,或者认为答案没有帮助。我会假装是后者,因为——无论什么叫做“蟒蛇”——这是正确的策略。除非你已经排除了,或者已经准备好处理a为False的情况,否则你需要一个比不是:更严格的测试。你可以用这样的方法:
if isinstance(a, numpy.ndarray) and not a.size:
do_stuff
elif isinstance(a, collections.Sized) and not a:
do_stuff
第一个测试是对上面@Mike的回答的回应。第三行也可以替换为:
elif isinstance(a, (list, tuple)) and not a:
如果您只想接受特定类型(及其子类型)的实例,或者使用:
elif isinstance(a, (list, tuple)) and not len(a):
如果不进行显式类型检查,您就可以离开,但前提是周围的上下文已经向您保证a是您准备处理的类型的值,或者如果您确定您不准备处理的那些类型将引发您准备好处理的错误(例如,如果您在未定义的值上调用len,则为TypeError)。总的来说,“蟒蛇”习俗似乎走到了最后一条路。像鸭子一样挤压它,如果它不知道如何呱呱叫,就让它养一只鸭子。不过,你仍然需要考虑你正在做什么样的假设,以及你没有准备好正确处理的案例是否真的会在正确的地方出错。Numpy数组是一个很好的例子,其中仅仅盲目地依赖len或布尔类型转换可能无法实现预期的效果。
其他回答
def list_test (L):
if L is None : print('list is None')
elif not L : print('list is empty')
else: print('list has %d elements' % len(L))
list_test(None)
list_test([])
list_test([1,2,3])
有时单独测试无和空是很好的,因为这是两种不同的状态。上述代码产生以下输出:
list is None
list is empty
list has 3 elements
虽然没有一件事是假的,但这毫无价值。所以,如果你不想单独测试“无”,你不必这么做。
def list_test2 (L):
if not L : print('list is empty')
else: print('list has %d elements' % len(L))
list_test2(None)
list_test2([])
list_test2([1,2,3])
预期产量
list is empty
list is empty
list has 3 elements
从python3开始,您可以使用
a == []
检查列表是否为空
编辑:这也适用于python2.7。。
我不知道为什么有这么多复杂的答案。这很清楚明了
我更喜欢以下内容:
if a == []:
print "The list is empty."
在真值测试中,空列表本身被认为是错误的(请参见python文档):
a = []
if a:
print("not empty")
达伦·托马斯的回答:
编辑:反对测试的另一点空列表为False:多态性?你不应该依赖列表是列表。它应该只是像鸭子一样呱呱叫-你怎么样让你的duckCollection呱呱叫当它没有元素时为“False”?
duckCollection应该实现__nonzero_或__len__,因此if-a:将毫无问题地工作。
要检查列表是否为空,可以使用以下两种方法。但请记住,我们应该避免显式检查序列类型的方式(这是一种不太像Python的方式):
def enquiry(list1):
return len(list1) == 0
# ––––––––––––––––––––––––––––––––
list1 = []
if enquiry(list1):
print("The list isn't empty")
else:
print("The list is Empty")
# Result: "The list is Empty".
第二种方式是一种更具Python风格的方式。这种方法是一种隐式检查方法,比前一种方法更可取。
def enquiry(list1):
return not list1
# ––––––––––––––––––––––––––––––––
list1 = []
if enquiry(list1):
print("The list is Empty")
else:
print("The list isn't empty")
# Result: "The list is Empty"