Pythonic写法:简化多值匹配的if条件判断
简化该Python条件判断的几种方法
使用成员运算符
in
把目标字符串存入集合(查找效率优于列表),只需调用一次lower(),代码更简洁:if user_input.lower() in {'yes', 'y'}: print('Done!')提前缓存转换后的结果
如果后续还要用到小写形式的输入,先将其赋值给变量,避免重复调用lower():lower_input = user_input.lower() if lower_input == 'yes' or lower_input == 'y': print('Done!')前缀匹配(按需使用)
若业务允许匹配以yes或y开头的输入(比如yes please),可以用startswith:if user_input.lower().startswith(('yes', 'y')): print('Done!')
内容的提问来源于stack exchange,提问作者morcilloso
相关产品推荐
相关产品推荐

