首页 > 解决方案 > 更简单的案例列表

问题描述

我必须测试很多情况,但是这个解决方案不是很优雅:

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']]

标签: pythonlistif-statementcase-statement

解决方案


用于next从生成器中获取第一个值。

x = next((val for (num, val) in L if num in name), 'default value')

的第一个参数next是要消耗的生成器,第二个参数是如果生成器被完全消耗而不产生值的默认值。


推荐阅读