如何检查数组是否为空?

105

如何检查数组是否不为空?我尝试了这样做:

if not self.table[5] is None:

这是正确的方式吗?


1
@birryree:不是重复的问题。bool([]) == bool(array([])),但是bool([0]) != bool(array([0])) - endolith
8个回答

109

问题中没有提到numpy。如果你所说的 array 指的是列表,那么如果将列表视为布尔值,则列表有项时返回True,为空时返回False。

l = []

if l:
    print "list has items"

if not l:
    print "list is empty"

3
这种方法很危险,因为例如bool(numpy.array([0]))评估为False。Remi使用a.size的测试是正确的。 - Drew Frank
是的,这是错误的,不应该有这么多赞。 - endolith
6
当使用列表时,此答案是正确的。如果a是一个列表,a.size将无法工作。提问者应该更具体地说明数据类型。 - chthonicdaemon
9
@DrewFrank,这是对问题的正确回答。你正在“杜撰”问题,然后声称答案是错误的。 - volcano
@volcano 看起来并不是,OP明确指出了一个“数组”,而不是一个“列表”... - gt6989b
2
@gt6989b,您的“清楚”是指不清楚吗?如果没有明确说明,人们可能会认为提问者是在询问有关列表(list)的问题,但使用了错误的单词。我的回答非常明确地解释了这个假设。我猜测提问者更有可能是在询问列表而不是NumPy数组的问题。 - John Kugelman

65

使用将 a 定义为一个 NumPy数组,然后执行以下操作:

if a.size:
   print('array is not empty')

(在Python中,像[1,2,3]这样的对象被称为列表(lists),而不是数组(arrays)。)


仅仅为了检查一个列表是否为空而使用numpy似乎过于繁琐。 - Pengo
6
@Pengo: 我并没有建议将列表转换为NumPy数组。这个答案假定 'a' 已经是一个NumPy数组。在Python中谈论“数组”很快会涉及到NumPy数组,因为原生的Python没有Array对象,只有列表(Lists)。 - Remi

10
< p > len(self.table)检查数组的长度,因此您可以使用if语句来判断列表的长度是否大于0(非空):

Python 2:

if len(self.table) > 0:
    #Do code here

Python 3:

if(len(self.table) > 0):
    #Do code here

也可以使用

if self.table:
    #Execute if self.table is not empty
else:
    #Execute if self.table is empty

判断列表是否为空。


8
if self.table:
    print 'It is not empty'

也可以


7
print(len(a_list))

许多语言都有len()函数,在Python中也可以使用它来回答您的问题。如果输出不是0,则列表不为空。

使用数组包中的array('d')进行操作。 - Vladimir Simoes da Luz Junior

4
如果您在谈论 Python 的实际 array(通过 import array from array 可用),那么最少惊讶原则适用,并且您可以检查它是否为空,方法与检查列表是否为空相同。
from array import array
an_array = array('i') # an array of ints

if an_array:
    print("this won't be printed")

an_array.append(3)

if an_array:
    print("this will be printed")

4

我还无法进行评论,但需要提到的是,如果您使用的是包含多个元素的numpy数组,则会失败:

if l:
    print "list has items"

elif not l:
    print "list is empty"

错误将会是:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

4

一种简单的方法是使用布尔表达式:

if not self.table[5]:
    print('list is empty')
else:
    print('list is not empty')

或者您可以使用另一个布尔表达式:
if self.table[5] == []:
    print('list is empty')
else:
    print('list is not empty')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接