例如,如果通过以下步骤:
如何检查a是否为空?
1 2
| if not a:
print("List is empty") |
使用空列表的隐式booleanness非常符合python的风格。
python的方法来自PEP 8风格指南(Yes表示"推荐",No表示"不推荐"):
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
1 2 3 4 5
| Yes: if not seq:
if seq:
No: if len(seq):
if not len(seq): |
我更喜欢明确地说:
1 2
| if len(li) == 0:
print('the list is empty') |
这样,li就是一个序列(列表),并且我们想测试它的大小,这是100%清楚的。我对if not li: ...的问题是,它给人的错误印象是li是一个布尔变量。
其他人似乎在推广这个问题,而不仅仅是列表,所以我想我应该为许多人可能使用的另一种类型的序列添加一个警告,特别是因为这是"python test empty array"第一次出现谷歌。
其他方法对numpy数组不起作用
您需要小心使用numpy数组,因为对list或其他标准容器有效的其他方法对numpy数组无效。我将在下面解释原因,但简而言之,首选的方法是使用size。
"pythonic"方法不起作用:第1部分
"pythonic"方法在numpy数组中失败,因为numpy试图将数组转换为bool的数组,而if x试图同时计算所有这些bool,以获得某种聚合真值。但是这没有任何意义,所以你得到一个ValueError:
1 2 3
| >>> x = numpy.array([0,1])
>>> if x: print("x")
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() |
"pythonic"方法不起作用:第2部分
但至少上面的例子告诉你它失败了。如果恰好有一个只有一个元素的numpy数组,则if语句将"工作",因为您不会得到错误。但是,如果这个元素恰好是0(或0.0,或false,…),则if语句将错误地导致false:
1 2 3 4
| >>> x = numpy.array([0,])
>>> if x: print("x")
... else: print("No x")
No x |
但是很明显x存在并且不是空的!这个结果不是你想要的。
使用
len可以得到意想不到的结果
例如,
1
| len( numpy.zeros((1,0)) ) |
返回1,即使数组中没有元素。
numpythonic方式
正如在scipy FAQ中所解释的,在您知道您有一个numpy数组的所有情况下,正确的方法是使用if x.size:
1 2 3 4 5 6 7 8 9 10 11 12 13
| >>> x = numpy.array([0,1])
>>> if x.size: print("x")
x
>>> x = numpy.array([0,])
>>> if x.size: print("x")
... else: print("No x")
x
>>> x = numpy.zeros((1,0))
>>> if x.size: print("x")
... else: print("No x")
No x |
如果您不确定它是list、numpy数组还是其他什么,您可以将这种方法与@dubiousjim给出的答案结合使用,以确保对每种类型使用正确的测试。不是很"python化",但事实证明numpy故意破坏了python性,至少在这个意义上是这样。
如果您需要做的不仅仅是检查输入是否为空,而且正在使用其他numpy特性,比如索引或数学操作,那么强制输入为numpy数组可能更有效(当然也更常见)。有一些很好的函数可以快速完成这一任务—最重要的是numpy.asarray。这将接受您的输入,如果它已经是一个数组,则什么也不做,如果它是一个列表、元组等,则将您的输入包装成一个数组,并可选地将其转换为您选择的dtype。所以它非常快,它确保你能假设输入是一个numpy数组。我们通常甚至只是使用相同的名称,因为转换到数组不会使它回到当前作用域之外:
1
| x = numpy.asarray(x, dtype=numpy.double) |
这将使x.size检查在我在本页看到的所有情况下都能工作。
Best way to check if a list is empty
For example, if passed the following:
How do I check to see if a is empty?
短答:
将列表放在布尔上下文中(例如,使用if或while语句)。如果它是空的,它将测试False,否则将测试True。例如:
1 2
| if not a: # do this!
print('a is an empty list') |
诉诸权威
PEP 8, Python标准库中Python代码的官方Python风格指南,声明:
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
1 2 3 4 5
| Yes: if not seq:
if seq:
No: if len(seq):
if not len(seq): |
我们应该期望标准库代码应该尽可能地高性能和正确。但为什么会这样,为什么我们需要这种指导?
解释
我经常从经验丰富的新手程序员那里看到这样的代码:
1 2
| if len(a) == 0: # Don't do this!
print('a is an empty list') |
懒语言的用户可能会这样做:
1 2
| if a == []: # Don't do this!
print('a is an empty list') |
这些在他们各自的其他语言中是正确的。在Python中,这甚至在语义上是正确的。
但是我们认为它不符合Python,因为Python通过布尔强制在列表对象的接口中直接支持这些语义。
从文档中(特别注意包含空列表[]):
By default, an object is considered true unless its class defines
either a __bool__() method that returns False or a __len__() method
that returns zero, when called with the object. Here are most of the built-in objects considered false:
constants defined to be false: None and False.
zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
empty sequences and collections: '', (), [], {}, set(), range(0)
和数据模型文档:
object.__bool__(self)
Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined,
__len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__()
nor __bool__(), all its instances are considered true.
和
object.__len__(self)
Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __bool__() method and whose __len__() method returns zero is considered to be false in a Boolean context.
所以不用这个:
1 2
| if len(a) == 0: # Don't do this!
print('a is an empty list') |
或:
1 2
| if a == []: # Don't do this!
print('a is an empty list') |
这样做:
1 2
| if not a:
print('a is an empty list') |
做python通常会在性能上得到回报:
它有回报吗?(注意,执行相同操作的时间越短越好:)
1 2 3 4 5 6 7
| >>> import timeit
>>> min(timeit.repeat(lambda: len([]) == 0, repeat=100))
0.13775854044661884
>>> min(timeit.repeat(lambda: [] == [], repeat=100))
0.0984637276455409
>>> min(timeit.repeat(lambda: not [], repeat=100))
0.07878462291455435 |
对于scale,这里是调用函数、构造和返回空列表的成本,您可以从上面使用的空值检查的成本中减去这些成本:
1 2
| >>> min(timeit.repeat(lambda: [], repeat=100))
0.07074015751817342 |
我们可以看到,与0相比,使用内置函数len检查长度或者检查空列表的性能要比使用文档中描述的语言内置语法低得多。
为什么?
对于len(a) == 0检查:
首先,Python必须检查全局变量以查看len是否被隐藏。
然后必须调用函数load 0,用Python(而不是C)进行等式比较:
1 2 3 4 5 6 7 8
| >>> import dis
>>> dis.dis(lambda: len([]) == 0)
1 0 LOAD_GLOBAL 0 (len)
2 BUILD_LIST 0
4 CALL_FUNCTION 1
6 LOAD_CONST 1 (0)
8 COMPARE_OP 2 (==)
10 RETURN_VALUE |
对于[] == [],它必须构建一个不必要的列表,然后再次在Python的虚拟机中执行比较操作(与C相反)
1 2 3 4 5
| >>> dis.dis(lambda: [] == [])
1 0 BUILD_LIST 0
2 BUILD_LIST 0
4 COMPARE_OP 2 (==)
6 RETURN_VALUE |
"python"方法是一个更简单和更快的检查,因为列表的长度缓存在对象实例头:
1 2 3 4
| >>> dis.dis(lambda: not [])
1 0 BUILD_LIST 0
2 UNARY_NOT
4 RETURN_VALUE |
证据来自C源码和文档
PyVarObject
This is an extension of PyObject that adds the ob_size field. This is only used for objects that have some notion of length. This type does not often appear in the Python/C API. It corresponds to the fields defined by the expansion of the PyObject_VAR_HEAD macro.
从Include/listobject.h中的c源代码:
1 2 3 4 5 6 7 8 9 10
| typedef struct {
PyObject_VAR_HEAD
/* Vector of pointers to list elements. list[0] is ob_item[0], etc. */
PyObject **ob_item;
/* ob_item contains space for 'allocated' elements. The number
* currently in use is ob_size.
* Invariants:
* 0 <= ob_size <= allocated
* len(list) == ob_size |
我喜欢研究这个,我花了很多时间整理我的答案。如果你认为我遗漏了什么,请在评论中告诉我。
空列表本身在真值测试中被认为是假的(参见python文档):
1 2 3
| a = []
if a:
print"not empty" |
@Daren托马斯
EDIT: Another point against testing
the empty list as False: What about
polymorphism? You shouldn't depend on
a list being a list. It should just
quack like a duck - how are you going
to get your duckCollection to quack
''False'' when it has no elements?
您的duckCollection应该实现__nonzero__或__len__,这样if a:就可以正常工作了。
帕特里克(公认)的答案是正确的:if not a:是正确的做法。Harley Holcombe的回答是正确的,这是PEP 8风格指南。但是没有一个答案能解释为什么遵循这个习惯用法是一个好主意——即使您个人发现它不够明确或让Ruby用户感到困惑或其他什么。
Python代码和Python社区都有很强的习惯用法。对于任何有Python经验的人来说,遵循这些习惯用法可以使您的代码更容易阅读。当你违反了这些习惯用语,这是一个强烈的信号。
确实,if not a:不能将空列表与None、数值0、空元组、空用户创建的集合类型、空用户创建的非完全收集类型、或作为标量的单元素NumPy数组等区分开来。有时候明确这一点很重要。在这种情况下,你知道你想要明确什么,所以你可以对它进行测试。例如,if not a and a is not None:表示"除了None之外的任何falsey内容",而if len(a) != 0:表示"只有空序列—这里除了序列之外的任何内容都是错误的",以此类推。除了准确地测试您想要测试的内容之外,这还向读者发出信号,表明该测试非常重要。
但是当您没有任何明确的内容时,除了if not a:之外的任何内容都会误导读者。当重要的事情不重要的时候,你是在发出信号。(你也可能使代码变得不那么灵活,或者变慢,或者诸如此类,但这些都不那么重要。)如果你习惯性地这样误导读者,那么当你确实需要做出区分时,它就会被忽略,因为你的代码中到处都是"狼来了"。
我认为以下是首选:
1 2
| if not a:
print("The list is empty or null") |
为什么要检查?
似乎没有人会在一开始就质疑你是否需要测试这份清单。因为您没有提供额外的上下文,所以我可以想象您可能一开始就不需要做这个检查,但是不熟悉Python中的列表处理。
我认为最符合python风格的方法是根本不进行检查,而是直接处理列表。这样它就会做正确的事,无论是空的还是满的。
1 2 3 4 5 6
| a = []
for item in a:
<do something with item>
<rest of code> |
这样做的好处是可以处理a的任何内容,而不需要对空值进行特定的检查。如果a为空,依赖块将不执行,解释器将进入下一行。
如果确实需要检查数组是否为空,那么其他答案就足够了。
len()是用于Python列表、字符串、dict和集合的O(1)操作。Python在内部跟踪这些容器中的元素数量。
JavaScript也有类似的真假概念。
我写了:
1 2
| if isinstance(a, (list, some, other, types, i, accept)) and not a:
do_stuff |
结果是-1。我不确定这是因为读者们反对这一策略,还是因为他们认为这样的答案毫无帮助。我将假设是后者,因为——无论什么被认为是"python式"的——这是正确的策略。除非您已经排除了这种可能性,或者准备处理a是False的情况,否则您需要一个比仅仅if not a:更严格的测试。你可以这样用:
1 2 3 4
| if isinstance(a, numpy.ndarray) and not a.size:
do_stuff
elif isinstance(a, collections.Sized) and not a:
do_stuff |
第一个测试是对上面@Mike的回答的响应。第三行也可改为:
1
| elif isinstance(a, (list, tuple)) and not a: |
如果您只想接受特定类型(及其子类型)的实例,或使用:
1
| elif isinstance(a, (list, tuple)) and not len(a): |
你可以没有显式类型检查,如果周围的环境已经向你保证a是一个值类型的你准备处理,或者如果你确定类型不准备处理会提高错误(例如,TypeError如果你叫len的值的定义),你准备处理。一般来说,"python式"约定似乎走的是最后一条路。像鸭子一样挤压它,如果它不知道如何嘎嘎叫,就让它举起一只鸭子镜。不过,您仍然需要考虑您所做的类型假设,以及您没有准备好正确处理的情况是否真的会在正确的位置出错。Numpy数组是一个很好的例子,它只是盲目地依赖len或布尔类型转换,可能无法准确地执行您所期望的操作。
Python对空的处理非常统一。鉴于以下几点:
1 2 3 4 5 6 7 8 9 10
| a = []
.
.
.
if a:
print("List is not empty.")
else:
print("List is empty.") |
只需用"if"语句检查列表a是否为空。根据我所读到的和所学到的,这是查看列表或元组是否为空的"python式"方法。
我使用的一些方法:
1 2 3 4 5 6
| if not a:
print"list is empty"
if len(a) == 0:
print"list is empty" |
从真值测试文档:
这里列出的值之外的所有值都被认为是True
NoneFalse任何数字类型的零,例如,
0、
0.0、
0j。任何空序列,例如,
''、
()、
[]。任何空映射,例如
{}。用户定义类的实例,如果类定义了
__bool__()或
__len__()方法,则该方法返回整数0或bool值
False。
可以看出,空列表[]是假的,所以对布尔值做什么听起来效率最高:
1 2
| if not a:
print('"a" is empty!') |
下面是一些检查列表是否为空的方法:
1)相当简单的python方法:
1 2
| if not a:
print("a is empty") |
在Python中,空容器如列表、元组、集、dict、变量等被视为False。可以简单地将列表视为谓词(返回一个布尔值)。True值表示它是非空的。
2)非常明确的方法:使用len()查找长度,检查是否等于0:
1 2
| if len(a) == 0:
print("a is empty") |
3)或将其与匿名空列表进行比较:
1 2
| if a == []:
print("a is empty") |
4)另一个愚蠢的方法是使用exception和iter():
1 2 3 4 5
| try:
next(iter(a))
# list has elements
except StopIteration:
print("Error: a is empty") |
我更喜欢以下内容:
1 2
| if a == []:
print"The list is empty." |
1 2 3 4 5 6 7 8
| 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]) |
有时单独测试None和空性是很好的,因为它们是两种不同的状态。上面的代码产生如下输出:
1 2 3
| list is None
list is empty
list has 3 elements |
虽然亚南的虚伪是毫无价值的。因此,如果不想对None-ness进行单独的测试,就不必这样做。
1 2 3 4 5 6 7
| 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]) |
产生预期的
1 2 3
| list is empty
list is empty
list has 3 elements |
方法1(首选):
1 2
| if not a :
print ("Empty") |
方法2:
1 2
| if len(a) == 0 :
print("Empty" ) |
方法3:
1 2
| if a == [] :
print ("Empty") |
已经给出了很多答案,其中很多都很好。我只是想把支票加进去
还将传递None和其他类型的空结构。如果你真的想检查一个空列表,你可以这样做:
1 2
| if isinstance(a, list) and len(a)==0:
print("Received an empty list") |
我们可以用一个简单的if else:
1 2 3 4 5
| list=[]
if len(list)==0:
print ("list is empty")
else:
print ("list is not empty") |
您可以检查数组的长度是否为零。如果数组的长度为零,那么它就是空的。试试以下:
1 2
| a = []
if len(a)==0 : print"List is empty" |
另一个简单的方法是
1 2 3 4 5
| a = []
if len(a) == 0:
print("Empty")
else:
print(" Not empty") |
从python3开始,您可以使用
检查列表是否为空
编辑:这也适用于python2.7 ..
我不知道为什么会有这么多复杂的答案。这是非常清楚和直接的
受到@dubiousjim的解决方案的启发,我建议使用一个额外的通用检查来检查它是否是可迭代的
1 2 3
| import collections
def is_empty(a):
return not a and isinstance(a, collections.Iterable) |
注意:字符串被认为是可迭代的。-添加and not isinstance(a,(str,unicode))如果您想要排除空字符串
测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| >>> is_empty('sss')
False
>>> is_empty(555)
False
>>> is_empty(0)
False
>>> is_empty('')
True
>>> is_empty([3])
False
>>> is_empty([])
True
>>> is_empty({})
True
>>> is_empty(())
True |
检查是否:len(list) == 0返回:True
1
| print('not empty' if a else 'empty') |
更实际一点:
简单的方法是检查长度是否等于零。
1 2
| if len(a) == 0:
print("a is empty") |
您甚至可以像这样尝试使用bool()
1 2 3 4
| a = [1,2,3];
print bool(a); # it will return True
a = [];
print bool(a); # it will return False |
我喜欢这种检查列表是否为空的方法。
非常方便和有用。
只需使用is_empty()或make函数,如:-
1 2 3 4 5 6 7
| def is_empty(any_structure):
if any_structure:
print('Structure is not empty.')
return True
else:
print('Structure is empty.')
return False |
它可以用于任何data_structure,比如列表、元组、字典等等。通过这些,您可以使用is_empty(any_structure)多次调用它。
空列表的真值是False,而非空列表的真值是True。
如果要检查列表是否为空;
1 2 3
| l = []
if l:
# do your stuff. |
如果您想要检查列表中的所有值是否为空。
1 2 3
| l = ["", False, 0, '', [], {}, ()]
if all(bool(x) for x in l):
# do your stuff. |
然而,对于空列表,这将是正确的。
1 2 3 4 5
| def empty_list(lst):
if len(lst) ==0:
return false
else:
return all(bool(x) for x in l) |
现在你可以使用:
1 2
| if empty_list(lst):
# do your stuff. |
To check whether a list is empty or not you can use two following ways. But remember, we should avoid the way of explicitly checking for a sequence or list (it's a less pythonic way):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| def Enquiry(list1):
if len(list1) == 0:
return 0
else:
return 1
# ––––––––––––––––––––––––––––––––
list1 = []
if Enquiry(list1):
print ("The list isn't empty")
else:
print("The list is Empty")
# Result:"The list is Empty". |
The second way is a more pythonic one. This method is an implicit way of checking and much more preferable than the previous one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| def Enquiry(list1):
if not list1:
return 1
else:
return 0
# ––––––––––––––––––––––––––––––––
list1 = []
if Enquiry(list1):
print ("The list is Empty")
else:
print ("The list isn't empty")
# Result:"The list is Empty" |
希望这个有帮助。
非官方的方法:
1 2 3 4 5
| a = []
try:
print(a[-1])
except IndexError:
print("List is empty") |
我想人们建议
1 2
| if len(list1) == 0:
print("is a good way") |
或者len,你可以数一下
1 2
| if list1.__ len__()==0:
print("list1 is empty") |
你可以用另一种方法
1 2
| if list1.__ sizeof__() == 40:
print("list1 is empty") |
空列表的大小总是40。
如果列表为空,Collection.Any()总是返回False。