python-根据值列表检查多个变量
如果任何变量与某些字符串匹配,我有一段代码需要运行。代码看起来很长而且不是很pythonic:
if candidate_job_title in ('ERROR', 'NOT AVAILABLE') or candidate_company in ('ERROR', 'NOT AVAILABLE') or candidate_location in ('ERROR', 'NOT AVAILABLE'):
# do something
我能想到的最好的就是这个,我还能做些什么来使它更具可读性?
if any (v in ('ERROR', 'NOT AVAILABLE') for v in (candidate_job_title, candidate_company, candidate_location):
# do something
回答
如果这些值是可散列的,您可以使用设置交集:
if {candidate_job_title, candidate_company, candidate_location} & {'ERROR', 'NOT AVAILABLE'}:
...