首先要知道这么一句话:如果有某种内容,则几乎所有值都将为True。
下面具体来解释一下这句话:
- 在字符串中,除空字符串外,其他任何字符串均为True
- 在数字中,除0外,其他任何数字均为True
- 在列表、元组、集合和字典中,除空列表、空元组、空集合和空字典外,其他任何列表、元组、集合和字典均为True
例如,以下项bool值均为True
判断项 | bool值 |
---|---|
bool(‘abc’) | True |
bool(123) | True |
bool([‘apple’,‘orange’,banana’]) | True |
而以下项bool值均为False
判断项 | bool值 |
---|---|
bool(False) | False |
bool(None) | False |
bool(’’) | False |
bool(0) | False |
bool([]) | False |
bool(()) | False |
bool({}) | False |
故如需判断列表为空,只需
if listName:
'列表不为空时执行的代码'
else:
'列表为空时执行的代码'
或
if not listName:
'列表为空时执行的代码'
else:
'列表不为空时执行的代码'