如何检查数组是否为空?

时间:2011-02-23 01:48:56

标签: python

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

if not self.table[5] is None:

这是正确的方法吗?

8 个答案:

答案 0 :(得分:58)

问题中没有提到numpy。如果通过 array 表示list,那么如果将列表视为布尔值,如果它有项目则会产生True,如果它是空的则会产生False。

l = []

if l:
    print "list has items"

if not l:
    print "list is empty"

答案 1 :(得分:51)

a作为 numpy array ,请使用:

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

(在Python中,[1,2,3]之类的对象称为列表,而不是数组。)

答案 2 :(得分:7)

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

也很好

答案 3 :(得分:5)

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

查看列表是否为空。

答案 4 :(得分:1)

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

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')

答案 5 :(得分:1)

我还没有发表评论,但应该提到的是,如果你使用带有多个元素的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()

答案 6 :(得分:1)

print(len(a_list))

由于许多语言具有len()功能,因此在Python中这适用于您的问题。 如果输出不是0,则列表不为空。

答案 7 :(得分:1)

如果你在谈论Python的实际array(通过import array from array提供),那么最不惊讶的原则适用,你可以像你一样检查它是否为空; d检查列表是否为空。

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")
相关问题