“空”值(如空列表、空字符串、空元组、空字典等),在Python中,以下值在布尔上下文中被视为 False
:
None
False
- 数值
0
(包括0.0
、0j
等) - 空序列(如空字符串
""
、空列表[]
、空元组()
) - 空集合
set()
- 空字典
{}
- 空
frozenset()
因此,if not str_list:
可以用来检查 str_list
是否为 None
或其他“空”值。以下是一个示例:
def is_substr_in_list(substr: str, str_list=None):
if not str_list:
return False
return any(substr in s for s in str_list)
# 示例调用
x = "test"
result = is_substr_in_list(x, None)
print(result) # 输出: False
result = is_substr_in_list(x, [])
print(result) # 输出: False
result = is_substr_in_list(x, ["this is a test", "another string"])
print(result) # 输出: True