Python 更简单的案例列表

Python 更简单的案例列表,python,list,if-statement,case-statement,Python,List,If Statement,Case Statement,我必须测试很多案例,但这个解决方案不是很优雅: 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 有没有一种方法可以通过列表来

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

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

是的,它被称为循环

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
的第一个参数是要使用的生成器,第二个参数是默认值,如果生成器完全使用而没有生成值。

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

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

next
的第一个参数是要使用的生成器,第二个参数是默认值,如果生成器完全使用而没有生成值。

很好的解决方案!如果找不到匹配项,是否有一种很好的方法来设置默认情况,或者我是否需要一个
try
/
,除了StopIteration
?如果不希望引发StopIteration,可以使用。这里不需要尝试例外。@Basj
next((如果名称中有num,则L中的(num,val)为val),'default value')
会很好。很好的解决方案!如果找不到匹配项,是否有一种很好的方法来设置默认情况,或者我是否需要一个
try
/
,除了StopIteration
?如果不希望引发StopIteration,可以使用。这里不需要尝试例外。@Basj
next((如果名称中有num,则L中的(num,val)为val),“默认值”)
会很好。