2011-01-29 2 views
1

이것을 단순화하는 것이 가능합니까? 아마도 둘을 결합했을까요? 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: 
    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 

답변

9
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) 
+0

달콤한. 그냥 찾아 보았습니다 .get() http://docs.python.org/library/stdtypes.html#dict.get – Flowpoke

1

숫자 코드를 문자열 메시지에 매핑하는 것처럼 보입니다. 사전을 사용하십시오! 관찰 :

_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 
2

당신은 사전을 사용할 수 있습니다

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

평가 당신에게 흥미로운 일이 될 수 있습니다 ...

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

나는 투표하지 않겠지 만 ... 정말로, ** NO **. 나쁜 PHP 사례를 PHP에 그대로 두라 ^^ –

0
당신은 지역 주민() 또는 전역을 사용할 수 있습니다

() 변수를 구성하는 내장형 :

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) 
관련 문제