python - 更简单的案例列表
问题描述
我必须测试很多情况,但是这个解决方案不是很优雅:
if '22' in name:
x = 'this'
elif '35' in name:
x = 'that'
elif '2' in name: # this case should be tested *after* the first one
x = 'another'
elif '5' in name:
x = 'one'
# and many other cases
有没有办法用一个列表来完成这一系列的案例?
L = [['22', 'this'], ['35', 'that'], ['2', 'another'], ['5', 'one']]
解决方案
用于next
从生成器中获取第一个值。
x = next((val for (num, val) in L if num in name), 'default value')
的第一个参数next
是要消耗的生成器,第二个参数是如果生成器被完全消耗而不产生值的默认值。
推荐阅读
- rest - Spring REST Docs - 未记录的部分:
- sql - 如何在mongodb中查找重复记录数
- django - 如何从我的 Django 网页下载内容?
- python-3.x - 如何读取大 csv 文件并分别读取每一列?
- javascript - 我想在我用three.js 安装的obj 扩展模型的某些部分添加一个热点。我该怎么做?
- python - python click框架-oop方法中的自定义多命令实现
- python - 如何在 Kivy 的 .kv 文件中使用 for 循环创建标签?
- redux - 什么是 redux-loop 以及我们如何在 react native 中使用它
- c++ - 如何使用 cpp 查找我的本地系统日期格式?
- jsf - p:dataTable 中未正确返回所选行