Simplifying small code example
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?
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.
>>> tups = ('one', 33), ('two', 45), ('three', 76)
>>> for i, j in tups:
print(j)
33
45
76
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
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
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.
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 ...
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])
精彩评论