开发者

In Python, can I process two variables in one conditional?

开发者 https://www.devze.com 2023-02-07 03:26 出处:网络
Is it possible to simplify this? Perhaps combined the two? Teach me the ways of DRY :-\\ o = old_last_result

Is it possible to simplify this? Perhaps combined the two? Teach me the ways of DRY :-\

o = old_last_result
if o == 7:
    old_last_result_msg = result_7
elif o == 12:
    old_last_result_msg = result_12
elif o == 23:
    old_last_result_msg = result_23
elif o == 24:
    old_last_result_msg = result_24
elif o == 103:
    old_last_result_msg = result_103
elif o == 1000:
    old_last_result_msg = result_1000
else:
    old_last_result_msg = "Error code: #%s" % old_last_result

n = new_last_result
if n == 7:
    new_last_result_msg = result_7
elif n == 12:
    new_last_result_msg = result_12
elif n == 23:
   开发者_StackOverflow中文版 new_last_result_msg = result_23
elif n == 24:
    new_last_result_msg = result_24
elif n == 103:
    new_last_result_msg = result_103
elif n == 1000:
    new_last_result_msg = result_1000
else:
    new_last_result_msg = "Error code: #%s" % new_last_result


result_msgs = {
  7: result_7,
  12: result_12,
   ...
}

old_last_result_msg = result_msgs.get(old_last_result,
  "Error code: #%s" % old_last_result)
new_last_result_msg = result_msgs.get(new_last_result,
  "Error code: #%s" % new_last_result)


You can use dictionaries:

results = {7: result_7, ..., 1000: result_100}
old_last_result_msg = results.get(o, "Error code: #%s" % old_last_result)


You seem to be mapping numeric codes to string messages. Use dictionaries! Observe:

_result_msg = {
    7: result_7,
    12: result_12,
    # ... etc
}

o = old_last_result
try:
    old_last_result_msg = _result_msg[o]
except KeyError:
    old_last_result_msg = 'Error code: #%s' % o


eval may be interesting to you...

i = 7
result_7 = 'foo'
print eval('result_%s' % i)
> foo


You can use locals() or globals() builtin to construct the variable like:

var res = "result_%d"%o
if res in locals(): old_last_result_msg = locals()[res]
else:
    if res in globals(): old_last_result_msg = globals()[res]
    else: raise Exception("unexpected result:%s"%res)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号