在 Python 中检查列表是否为空的最佳方法是什么?

pythonserver side programmingprogramming

最好的方法是在列表对象上使用 not 运算符。如果列表为空,则返回 true,否则返回 false。

>>> L1=[]
>>> not L1
True
>>> L1=[1,2]
>>> not L1
False

另一种方法是检查列表的长度是否为零,这意味着它为空

>>> L1=[]
>>> len(L1)
0
>>> L1=[1,2]
>>> len(L1)
2

相关文章


有用资源