我在python中编写了一个解析一些字符串的脚本。
问题是我需要检查字符串是否包含某些部分。我发现的方式不够聪明。
这是我的代码:
if ("CondA" not in message) or ("CondB" not in message) or ("CondC" not in message) or ...:
有没有办法优化这个?对于这种情况,我还有 6 项其他检查。
我在python中编写了一个解析一些字符串的脚本。
问题是我需要检查字符串是否包含某些部分。我发现的方式不够聪明。
这是我的代码:
if ("CondA" not in message) or ("CondB" not in message) or ("CondC" not in message) or ...:
有没有办法优化这个?对于这种情况,我还有 6 项其他检查。
您可以使用any
功能:
if any(c not in message for c in ("CondA", "CondB", "CondC")):
...
使用带有any()
or的生成器all()
:
if any(c not in message for c in ('CondA', 'CondB', ...)):
...
在 Python 3 中,您还可以利用map()
惰性:
if not all(map(message.__contains__, ('CondA', 'CondB', ...))):