Skip to main content
 首页 » 编程设计

python之一个更简单的案例列表

2025年05月04日2452php

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

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 的第一个参数是要消耗的生成器,第二个参数是生成器完全消耗而未产生值时的默认值。