Basj
Basj

Reputation: 46381

A simpler list of cases

I have to test many cases, but this solution is not very elegant:

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

Is there a way to do this sequence of cases with a list?

L = [['22', 'this'], ['35', 'that'], ['2', 'another'], ['5', 'one']]

Upvotes: 1

Views: 42

Answers (2)

BallpointBen
BallpointBen

Reputation: 13750

Use next to take the first value from a generator.

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

The first argument of next is the generator to consume, and the second is the default value if the generator is entirely consumed without producing a value.

Upvotes: 3

Netwave
Netwave

Reputation: 42678

Yes, it is called looping:

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

Upvotes: 2

Related Questions