一个更简单的案例列表

A simpler list of cases

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

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

是的,它被称为循环:

for cond, val in L:
    if cond in name:
        x = val
        break

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

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

next 的第一个参数是要消耗的生成器,第二个参数是生成器完全消耗而没有产生值时的默认值。