tags:

views:

184

answers:

7

Lets pretend I have the following code.

num1 = 33
num2 = 45
num3 = 76
lst = ['one', 'two', 'three']

for item in lst:
    if item == 'one':
        print num1
    elif item == 'two':
        print num2
    elif item == 'three':
        print num3

Is there a way to make this more elegant when there is no correlation between the list and the print sentence? Meaning, is there a way to get rid of the ifs and elifs?

+5  A: 

You can of course use a dictionary, to look up the response:

lst = ['one', 'two', 'three']
resp = { 'one': num1, 'two': num2, 'three': num3 }

for item in lst:
  print resp[item]

This is still pretty static, though. Another approach would be object-orienting it, so you get to implement a function in the objects in lst that makes the decision.

unwind
+5  A: 
>>> tups = ('one', 33), ('two', 45), ('three', 76)
>>> for i, j in tups:
    print(j)


33
45
76
SilentGhost
+4  A: 

Is it intentional that your code ignores objects that are not mentioned in any if/elif clause? If so, use a dictionary with a default value of 'None' if the object is not found:

lst = ['one', 'two', 'three'] 
d = { 'one': 33, 'two': 45, 'three': 76}

for item in lst: 
    x = d.get(item)
    if x is not None:
        print x
Mark Byers
I guess you meant `if x is not None`
RaphaelSP
Oops, thanks! That's why it's a good idea to test all code, even if it is extremely simple!
Mark Byers
Yes, it was intensional.
Orjanp
+2  A: 

the whole logic of your if/else is equivalent to a dictionary's key and value pairs

d = {"one":33, "two":44, "three":76}

this part of your code

if item == 'one':
    print num1

is the same as

print d["one"]

like wise for the others

+1  A: 

If you have dictionary like this:

d = {"one":33, "two":44, "three":76}

You can print it like this:

for k in d.keys():
    print d[k]

This presumes that you do not care about the order.

Richie
+1  A: 

For your simple example a dictinary lookup poposed in other answers is the best. But sometimes you need to run completely different code for each condition, so the following idiom might be useful too:

class MyClass(object):

    def process(self, item):
        # Select the method to call based on item value
        return getattr(self, 'do_'+item)()

    def do_one(self):
        # do something here

    def do_two(self):
        # do something other here

    # ... other methods ...
Denis Otkidach
+1  A: 

When there's no correlation between the if clause and the prints, you can create a mapping dictionary to store the correlations. You need to be careful to map to the variable of numx, not the current value (thus the use of the eval function):

num1 = 33
num2 = 45
num3 = 76
lst = ['one', 'two', 'three']

map = {'one': 'num1', 'two': 'num2', 'three': 'num3'} 

for item in lst:
    print item in map and eval(map[item]) or 'Unknown'

If you're sure the item is in the map, the last line can be simplified further to:

    print eval(map[item])
Brian Frantz